为了合并函数和方法,我没有时间去理清术语,但我知道区别(通常)。从全局变量访问打印功能
我想通过命令行参数控制脚本运行的是什么函数。在这里和其他地方阅读了很多内容后,我正朝着下面的例子前进。
# 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
是:
- 其中MIGHT从命令行指定的方法;
- 当从命令行指定NO方法时的默认方法;
- 如果仅从命令行指定其他方法,则不执行。
让我承认,我可以通过消除第一和第三标准,简单地做事情做对自己更容易:
for row in cursor:
print row
for method_name in processing_methods:
globals[method_name](row)
但我真的不想总是打印每行中会出现什么有时候会有数百万行的结果。我做了一个未来的进口,希望能够解决我的问题 - 没有这样的运气。所以我做了一些探索:
>>> 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
?我做错了,还是仅仅是内置函数无法做到的事情?
什么是'processing_methods'?全球方法的白名单?你为什么不把它转换成'method_name' - >'implementation'字典?这样会更方便打字,但是您可以支持更广泛的用例并保持全局范围的清洁 – J0HN
就像这样:http:// ideone。com/qu6u4o – J0HN
@ J0HN'print_function'是错误的,因为一个OP的片段显示它是'__future __._ Feature'的一个实例,它是一段元数据,而不是一个函数。用'method ='print''试试看看它失败了。 – delnan