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

Ada*_*ris 6 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
Run Code Online (Sandbox Code Playgroud)

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

myscript.sh:

#!/bin/sh
python $@
Run Code Online (Sandbox Code Playgroud)

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

但我想要的是: ['firstParam','file with spaces.txt']

Mar*_*ers 8

"$@"改为使用:

#!/bin/sh
python "$@"
Run Code Online (Sandbox Code Playgroud)

输出:

$ /tmp/test.sh /tmp/test.py firstParam "file with spaces.txt"
['/tmp/test.py', 'firstParam', 'file with spaces.txt']
Run Code Online (Sandbox Code Playgroud)

/tmp/test.py定义为:

import sys
print sys.argv
Run Code Online (Sandbox Code Playgroud)


int*_*jay 5

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

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

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