2011-07-16 82 views
11

將bash變量傳遞給python腳本的最佳方式是什麼?我想這樣做如下:將bash變量傳遞給腳本?

$cat test.sh 
#!/bin/bash 

foo="hi" 
python -c 'import test; test.printfoo($foo)' 

$cat test.py 
#!/bin/python 

def printfoo(str): 
    print str 

當我試圖運行bash腳本,我得到一個語法錯誤:

File "<string>", line 1 
    import test; test.printfoo($foo) 
          ^
SyntaxError: invalid syntax 

回答

8

總之,這個工程:

... 
python -c "import test; test.printfoo('$foo')" 
... 

更新:

如果您認爲該字符串可能包含單引號(')如@Gordon在下面的評論中所說的,您可以在bash中輕鬆地轉義那些單引號。下面是在這種情況下一個替代解決方案:

... 
python -c "import test; test.printfoo('"${foo//\'/\\\'}"');" 
... 
+2

如果$ foo包含任何單引號或其他字符python解釋文字內容,這將失敗有趣。 @亞當的解決方案更強大... –

2

你必須使用雙引號來獲得變量替換慶典。類似於PHP。

$ foo=bar 
$ echo $foo 
bar 
$ echo "$foo" 
bar 
$ echo '$foo' 
$foo 

因此,這應該工作:

python -c "import test; test.printfoo($foo)" 
+0

也進一步得到,但現在有蟒側的錯誤,它說:NameError:名字「喜」沒有定義。 – Ravi

2

與argv的處理做吧。這樣你就不必導入它,然後從解釋器中運行它。

test.py

import sys 

def printfoo(string): 
    print string 

if __name__ in '__main__': 
    printfoo(sys.argv[1]) 

python test.py testingout 
+0

我希望直接調用printfoo,因爲我有很多其他的需要從bash中調用參數的python函數。如果我爲他們所有人做主,那會更加複雜。 – Ravi

12

您可以使用os.getenv從Python的訪問環境變量:

import os 
import test 
test.printfoo(os.getenv('foo')) 

然而,爲了使環境變量從猛砸傳遞給它創建的任何過程,你需要將它們與export builtin出口:

foo="hi" 
export foo 
# Alternatively, the above can be done in one line like this: 
# export foo="hi" 

python <<EOF 
import os 
import test 
test.printfoo(os.getenv('foo')) 
EOF 

作爲使用環境變量的替代方法,您可以直接在命令行上傳遞參數。傳遞到Python中-c command之後的任何選項得到裝入sys.argv數組:

# Pass two arguments 'foo' and 'bar' to Python 
python - foo bar <<EOF 
import sys 
# argv[0] is the name of the program, so ignore it 
print 'Arguments:', ' '.join(sys.argv[1:]) 
# Output is: 
# Arguments: foo bar 
EOF