【问题标题】:Read argument with spaces in python script from a shell script从 shell 脚本中读取 python 脚本中带空格的参数
【发布时间】:2012-06-03 19:13:44
【问题描述】:

运行 python 脚本时如何读取带空格的参数?

更新

看来我的问题是我正在通过 shell 脚本调用 python 脚本:

这行得通:

> python script.py firstParam file\ with\ spaces.txt
# or
> python script.py firstParam "file with spaces.txt"

# script.py
import sys
print sys.argv

但是,不是当我通过脚本运行它时:

myscript.sh:

#!/bin/sh
python $@

打印:['firstParam', 'file', 'with', 'spaces.txt']

但我想要的是: ['firstParam', '带空格的文件.txt']

【问题讨论】:

    标签: python shell


    【解决方案1】:

    改用"$@"

    #!/bin/sh
    python "$@"
    

    输出:

    $ /tmp/test.sh /tmp/test.py firstParam "file with spaces.txt"
    ['/tmp/test.py', 'firstParam', 'file with spaces.txt']
    

    /tmp/test.py 定义为:

    import sys
    print sys.argv
    

    【讨论】:

      【解决方案2】:

      如果你想将参数从一个 shell 脚本传递给另一个程序,你应该使用"$@" 而不是$@。这将确保每个参数都被扩展为一个单词,即使它包含空格。 $@ 等价于$1 $2 ...,而"$@" 等价于"$1" "$2" ...

      例如,如果你运行:./myscript param1 "param with spaces":

      • $@ 将扩展为 param1 param with spaces - 四个参数。
      • "$@" 将扩展为 "param1" "param with spaces" - 两个参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-28
        • 2013-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多