为什么我会收到以下单行 Python 代码的语法错误?
python -c 'import re; if True: print "HELLO";'
File "<string>", line 1
import re; if True: print "HELLO";
^
SyntaxError: invalid syntax
下面的代码工作得很好:
python -c 'if True: print "HELLO";'
如何更改我的一行以从命令行在一行上执行我想要的脚本?
最佳答案
解决此限制的一个选项是使用换行转义序列 \n
以 $'string'
格式指定命令。
python -c $'import re\nif True: print "HELLO";'
注意:这是由 shell 支持的,例如 Bash和 Z shell (zsh
),但它不是有效的 POSIX Bourne shell (sh
).
作为mentioned by slaadvak ,这里还有一些其他解决方法:Executing Python multi-line statements in the one-line command-line
关于python - “If”语句和来自命令行的一行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44024221/