【发布时间】:2014-12-04 13:08:02
【问题描述】:
当使用 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 linux shell command-line