从shell脚本中读取python脚本中带空格的参数

时间:2012-05-29 14:33:27

标签: python shell

运行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','file with spaces.txt']

2 个答案:

答案 0 :(得分:8)

改为使用"$@"

#!/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

答案 1 :(得分:5)

如果要将参数从shell脚本传递到另一个程序,则应使用"$@"而不是$@。这将确保每个参数都作为单个单词扩展,即使它包含空格。 $@相当于$1 $2 ...,而"$@"相当于"$1" "$2" ...

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

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