python - 从 globals() 访问打印函数

标签 python python-2.7 python-import

提前为混淆函数和方法表示歉意,我现在没有时间整理术语,但我(一般)知道其中的区别。

我试图通过命令行参数控制我的脚本运行哪些函数。在这里和其他地方进行了大量阅读之后,我正在朝着以下示例的方向前进。

# After connecting to a database with MySQLdb and defining a cursor...

cursor.execute(some_query_stored_earlier)
for row in cursor:
    for method_name in processing_methods:    # ('method1','method2', ...)
        globals()[method_name](row)

(澄清: processing_methods 是用户通过命令行参数使用 nargs='*' 定义的字符串的元组。)

但是,我遇到了 print 的问题(这并不奇怪)。我想要print成为:

  • 可以从命令行指定的方法;
  • 未从命令行指定任何方法时的默认方法;
  • 如果仅从命令行指定了其他方法,则不执行。

让我承认,通过消除第一个和第三个标准并简单地执行以下操作,我可以让自己的事情变得更轻松:

for row in cursor:
    print row
    for method_name in processing_methods:
        globals[method_name](row)

但我真的不想总是打印每一行,有时会达到几百万行的结果。我做了一个 future 的导入,希望能解决我的问题 - 没有这样的运气。所以我做了一些探索:

>>> from __future__ import print_function
>>> print
<built-in function print>

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'print_function': _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 65536), '__package__': None}

>>> a = "Hello, world!"
>>> print(a)
Hello, world!
>>> globals()['print'](a)

Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    globals()['print'](a)
KeyError: 'print'              # Okay, no problem, obviously it's...

>>> globals()['print_function'](a)

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    globals()['print_function'](a)
AttributeError: _Feature instance has no __call__ method    # ...huh.

然后我又读了一点,然后 this Q&A促使更多的探索:

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> __builtins__
<module '__builtin__' (built-in)>
>>> 'print' in dir(__builtins__)
True                                  # now we're getting somewhere!
>>> __builtins__.print something
SyntaxError: invalid syntax           # fair enough.
>>> __builtins__.print('something')
SyntaxError: invalid syntax           # wait, what?
>>> dir(__builtins__.print)
SyntaxError: invalid syntax           # -_-

这里发生了一些我不明白的事情,并且 this other Q&A还没有说得更清楚。我认为解决我的特定问题的简单解决方案将是一个稍微尴尬的包装器,例如:

def printrows(row):
    print row             # assuming no future import, of course

但这让我发疯:为什么我无法访问 print通过全局字典?是我做错了,还是只是内置函数无法做到这一点?

最佳答案

当您第二次尝试打开新 shell 时(您在其中遇到所有这些语法错误),您是否忘记重复 from __future__ import print_function ?它对我有用:https://ideone.com/JOBAAk

关于python - 从 globals() 访问打印函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17352210/

相关文章:

python - 将类别值分配给 pandas 列中的所有行

python - 为什么我在局域网中不能访问我的Socket Server,而我在自己的电脑上可以访问?

python - 从 python 中的导入语句中查找

python - 在 python3 中未检测到模块,但在 python2 中工作

python - 使用键中的给定值迭代字典,直到到达自定义端点

Python:导入 "import file"

python argparse 如何在 [-h] 命令后继续程序?

python - 使用 BeautifulSoup 进行 Selenium 滚动和抓取会产生重复的结果

Python获取有关组策略的信息

python - 无法在 FOR 循环 Python 中解压元组对象