问题描述
想知道是否有办法在 repl 中只使用函数名调用 python 中的函数。
$ python -i interace.py
>>> load 834.png
>>> sharpen
>>> save
而不是
$ python -i interface.py
>>> load('834.png')
>>> sharpen()
>>> save()
原因是,我有一个具有上述格式的文件 instructions.txt
。我只想做$ python -i interface.py < instructions.txt
。
在我没有指令文件的时候,我可以手动输入指令。
解决方法
使用常规 Python 解释器无法做到这一点。 Function calls must include parentheses.
现在,您的指令看起来很像 shell 语法,所以也许您可以做的是编写自己的简单解析器。尝试查看 shlex 开始。
顺便说一句,如果有帮助,IPython 包含一个 %autocall
设置,几乎可以满足您的要求。
In [4]: print 'hello'
File "<ipython-input-4-5a1ef41e7057>",line 1
print 'hello'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello')?
In [5]: %autocall
Automatic calling is: Smart
In [6]: print 'hello'
------> print('hello')
------> print('hello')
hello
In [7]: print 834.png
------> print(834.png)
------> print(834.png)
File "<ipython-input-7-3d64d8523fdd>",line 1
print(834.png)
^
SyntaxError: invalid syntax