2012-05-29 121 views
3

如何在運行python腳本時用空格讀取參數?從shell腳本讀取python腳本中的空格參數

UPDATE

看起來像我的問題是,我通過一個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 [email protected] 

打印:[ 'firstParam', '文件', '有', 'spaces.txt']

但我想要的是: [ 'firstParam',「文件與空間。 TXT']

回答

6

使用"[email protected]"代替:

#!/bin/sh 
python "[email protected]" 

輸出:

$ /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 
+0

完美 - 「$ @」解決了這個問題。 –

4

如果你想從一個shell腳本到另一個程序傳遞參數,你應該使用"[email protected]"而不是[email protected]。這將確保每個參數都被擴展爲一個單詞,即使它包含空格。 [email protected]相當於$1 $2 ...,而"[email protected]"相當於"$1" "$2" ...

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