簡體   English   中英

從globals()訪問打印功能

[英]Accessing the print function from globals()

預先為混淆功能和方法而道歉,我目前沒有時間整理術語,但我知道這種區別(通常)。

我試圖通過命令行參數來控制腳本運行的功能。 在這里和其他地方進行了大量閱讀之后,我朝着以下示例的方向發展。

# 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為:

  • 在命令行中可能指定的方法中;
  • 從命令行指定NO方法時的默認方法;
  • 如果僅從命令行指定了OTHER方法,則不執行。

讓我承認,通過消除第一個和第三個條件,並且只需執行以下操作,我可以使自己更輕松一些:

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.

因此,我做了一些閱讀,然后這個問答環節引發了更多的探索:

>>> 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           # -_-

這里發生的事情我只是不了解,而其他問答也沒有使它更清楚。 我認為對我的特定問題的簡單解決方案將是一個稍微笨拙的包裝器,例如:

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

但這使我發瘋:為什么我不能通過globals字典訪問print 我做錯了嗎,還是只是內置函數無法做的事情?

當您打開第二個嘗試的新外殼from __future__ import print_function時,您是否忘記了from __future__ import print_function重復from __future__ import print_function (在那里您得到了所有這些語法錯誤)? 它對我有用https : //ideone.com/JOBAAk

如果您執行了其他看似無用的任務,那么它將按照我認為的預期工作。 我不是這里工作的內部專家,所以我無法解釋為什么這樣做有效,但確實如此。

>>> from __future__ import print_function
>>> row="Hello world"
>>> print = print
>>> globals()['print'](row)
Hello world

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM