【问题标题】:Writing python scripts directly on the command line直接在命令行编写python脚本
【发布时间】: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


    【解决方案1】:

    您在双引号内使用了双引号,它在您不期望的地方结束了您传递给 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
    

    【讨论】:

    • 这样做时,请记住只在脚本中的字符串周围使用双引号 ("),而不是单引号 (')。单引号会突然结束脚本并让 shell 尝试解释其余部分。
    • 或者用 `` 转义单引号
    • 是的,转义会让我感到难过,因为当时的内容不那么可读。
    【解决方案2】:

    另一个解决方案是转义你的内部双引号,这样 bash 就不会解析它们。像这样:

    $ python -c "
    import os
    
    if os.path.isfile(\"test\"):
        print \"test is a file\"
    else:
        print \"test is not a file\"
    "
    

    【讨论】:

      【解决方案3】:

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

      例子:

      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 代码中使用单引号inside,你必须用\ 转义它们;-)。

      输出是一样的。

      【讨论】:

        【解决方案4】:

        您可以使用通常所说的“here document”(如“使用此处的文档”)。这避免了使用python -c "..."python -c '...' 时的所有引用问题

        例如:

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

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

        【讨论】:

          猜你喜欢
          • 2013-12-17
          • 1970-01-01
          • 2013-12-25
          • 2014-12-24
          • 2013-05-13
          • 2021-03-20
          • 1970-01-01
          • 2016-11-22
          • 2023-03-21
          相关资源
          最近更新 更多