2016-03-25 176 views
1

當使用python的sh模塊, 我想運行'source'內置命令。Python的sh模塊 - 運行'source'命令

但我不能運行它,因爲sh應該有一個二進制參數。

如何使用sh模塊運行內置命令?

# source ./test.sh 

sh.source('./test.sh') # wrong usage 
sh.Command('source') # wrong usage 
+1

是否有一個特定的原因,你喜歡'sh'作爲適合這裏工作的工具,而不是'subprocess.Popen('source test.sh',shell = True)'? –

+1

......順便說一句,我認爲(過去曾爭論過,將來會再次爭論)sh'被誤導地命名,因爲它實際上並沒有調用shell。毫無疑問,考慮到它的名字,人們會預計它可以訪問'/ bin/sh'中的內置命令。 –

回答

4

要通過Python的sh模塊調用sh -c "source hello"

sh.sh('-c', 'source test.sh') 

這就是說,可以考慮使用subprocess.Popen()代替,其中包含遠魔少,因而表現更可預測:

# ...if hardcoding the script to source in your Python code 
subprocess.Popen('source ./test.sh', shell=True) 

# ...otherwise: 
subprocess.Popen(['source "[email protected]"', './test.sh'], shell=True) 

當一個數組傳遞給第一個參數subprocess.Popen,第一個參數被視爲運行源,後續參數變爲$1,$2等,該腳本運行期間允許通過shell=True調用/bin/sh字符串文本數組的組合。


但是:意圖和目的背後採購內容爲外殼一般是修改shell的狀態。無論是sh.sh還是subprocess.Popen(),shell只會持續該單一Python函數調用的調用,所以沒有任何狀態持續存在於將來shsubprocess調用中,使得這些用途中的任何一個都不可能真正實現您的目標。

真的要的是什麼可能更是這樣的:

sh.sh('-c', 'source ./test.sh; do-something-else-here') 

...您的do-something-else-here取決於更改外殼及其環境的source ./test.sh製造。

+0

除sh.sh - > sh.bash之外,它運行良好。非常感謝你。 – user3381542

+0

在subprocess.Popen的情況下,我應該添加可執行文件=「/ bin/bash」。 – user3381542

+1

@ user3381542,如果你的腳本被寫入來源於bash,它應該使用'.bash'擴展名而不是'.sh'(這意味着與任何兼容POSIX sh的shell)。 –