直接在命令行上编写python脚本

时间:2014-10-09 14:35:19

标签: 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的输出所以我只是字面意思地写了。

4 个答案:

答案 0 :(得分:4)

你在双引号内使用双引号,它结束了你传递给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

答案 1 :(得分:1)

另一个解决方案是逃避你的内部双引号,因此bash不会解析它们。像这样:

$ python -c "
import os

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

答案 2 :(得分:0)

使用单引号括起您的短程序,或者,如果您想使用双引号将其括起来,请使用\转义引号。

示例:

<强> 1。转义引号

$ python -c "
print \"hello\"
for i in (1,2,3):
    print i
"

输出:

hello
1
2
3

<强> 2。使用单引号

$ python -c '
print "hello"
for i in (1,2,3):
    print i
'

当然,如果你使用单引号括起你的程序,而你想在你的python代码中使用单引号 ,那么你必须用\来逃避它们。 - 。)

输出相同。

答案 3 :(得分:0)

您可以使用通常称为“here document”的内容(如“使用此处的文档”)。这可以避免在使用python -c "..."python -c '...'

时出现所有引用问题

例如:

#!/bin/sh
python <<EOF
print "hello"
for i in (1,2,3):
    print i
EOF

“here document”采用任意标记(“EOF”是一种常见的选择,但它可以是您知道在数据中任何其他位置都不会出现的任何字符串),并接受所有数据,直到找到一行包含该标记。

相关问题