python - 直接在命令行写python脚本

标签 python linux shell command-line

当使用 bash shell 命令时,有时在 python 中进行管道传输并编写一个简短的程序,然后可能将其管道传输到其他东西中是很有用的。我没有找到很多关于编写这样的 python 程序的文档,尽管它看起来像“-c”选项是可以使用的选项..但是当编写最简单的 python 程序时,编译器或者我应该说解释器会提示。请参见下面的示例:

$ python -c "
import os

if os.path.isfile("test"):
    print "test is a file"
else:
    print "test is not a file"
"

当输入最后一个 "时,解释器会提示。如果我把它放在一个文件中,它运行良好,但如果我像在命令行上那样输入它,我会出错。

$ python -c "
import os

if os.path.isfile("test"):
    print "test is a file"
else:
    print "test is not a file"
"
Traceback (most recent call last):
  File "<string>", line 4, in <module>
NameError: name 'test' is not defined

我不知道为什么口译员在这里提示。有人知道为什么这不起作用吗?

我真正想要的是这样的:

$ cat somefile | python -c "
import re

check = re.search(pattern, <file input>)
"

我不知道在这种情况下如何访问 cat 的输出,所以我只是按字面意思写了。

最佳答案

您在双引号内使用了双引号,双引号结束了您传递给 python 的引用字符串,在您不期望的地方。尝试用单引号替换外引号,就像我在这里所做的那样:

python -c '
import os

if os.path.isfile("test"):
    print "test is a file"
else:
    print "test is not a file"
'

如果您使用单引号来终止您传递给 python 的字符串,请确保在您的代码中只使用双引号。此外,如果你能保证 Bash 作为你的 shell 的可用性,你可以通过 using heredoc format 获得加分。相反:

$ python <<EOF
> print "I can put python code here"
> EOF
I can put python code here

关于python - 直接在命令行写python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281191/

相关文章:

javascript - Django 模板 : read database response text as HTML

python处理无尽的XML

php - ImageMagick bash 脚本问题

linux - LINUX 中的命令是如何处理的

linux - 脚本不在 bg 中运行

Python:分层切片

Python 2.7 - 如何将类属性(指针?)分配给变量(需要创建 Oz 式数据流变量)

c - printf 在共享内存中做了什么

python - 遍历 .tar.gz 目录并连接文件(不解压缩文件夹)

java - 无法从 java 运行 shell 脚本