python - 在单行命令行中执行多行语句

标签 python shell command-line heredoc

我正在使用带有 -c 的 Python 来执行单行循环,即:

python -c "for r in range(10): print 'rob'"

这很好用。但是,如果我在 for 循环之前导入一个模块,则会出现语法错误:

python -c "import sys; for r in range(10): print 'rob'"

  File "<string>", line 1
    import sys; for r in range(10): print 'rob'
              ^
SyntaxError: invalid syntax

如何解决这个问题?

对我来说,将它作为一个单行字很重要,这样我就可以将它包含在 Makefile 中。 .

最佳答案

你可以的

echo -e "import sys\nfor r in range(10): print 'rob'" | python

或者没有管道:

python -c "exec(\"import sys\nfor r in range(10): print 'rob'\")"

或者

(echo "import sys" ; echo "for r in range(10): print 'rob'") | python

SilentGhost's answerCrast's answer .

关于python - 在单行命令行中执行多行语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043453/

相关文章:

node.js - 如何在 Shell 中运行命令 CTRL+Z?

c - 在 Visual Studio 中放置要用作命令行参数的文件的位置

python - Selenium 网络驱动程序 : How to Download a PDF File with Python?

Python imaplib 下载 Gmail Text 而不下载完整附件

python - Numpy 压缩函数

linux - 用于查找文件系统使用情况的 Bash 脚本

python - 创建一个字典,其值每次使用时都会更新

linux - 打印文件中不以散列开头的所有行,并按特定列过滤

MySQL命令行导入导致sql文件变空

python - 如何使用 python 对齐 linux 输出