python - “If”语句和来自命令行的一行 Python 脚本

标签 python bash shell command-line

为什么我会收到以下单行 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 支持的,例如 BashZ 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/

相关文章:

linux - Shell脚本中波浪号 "~/<folder>"与〜/"<folder>"有什么不同

python - 创建一个具有未知键的字典并向其附加一个列表值?

python - 给出确切路径时出现 AWS Boto3 "Key pair does not exist"错误

python - 在文件 A 中包含一个 python 文件 B,其中 B 使用 A 中定义的变量

linux - 编码和进程名称

linux - 删除原始文件夹时删除符号链接(symbolic link)

Python - 如何阅读 Sharepoint excel 工作表特定工作表

macos - 如何将当前目录添加到 UNIX 中的搜索路径?

linux - 如何在 shell 脚本中使用 `time` 命令?

linux - 使用单个命令 : Linux 在所有目录下创建一个新目录