2013-03-27 160 views
-2

我正在linux中編寫python程序。在python程序中執行linux命令

在我的python程序中,我需要在python程序本身的另一個工作目錄中執行一個linux命令。

示例: 我的程序test.py位於目錄dir1/dir2中。

./wlst.sh是dir1/dir2/dir3/dir4中的程序。

所以我需要在位於dir2的python程序的dir4中執行.wlst.sh。

這怎麼辦?

+0

我假設你用Google搜索,發現['subprocess'](http://docs.python.org/2/library/subprocess.html #module-subprocess)模塊。你有什麼問題? – 2013-03-27 14:29:36

回答

0
import subprocess 
subprocess.call(['./wlst.sh'], cwd='dir1/dir2/dir3/dir4') 
+0

使用'chdir'會產生明顯的副作用; call()'更好地使用可選參數'cwd ='。 – Alfe 2013-03-27 14:51:59

3
import subprocess 
try: 
    output = subprocess.check_output(
    [ './wlst.sh' ], 
    cwd='dir1/dir2/dir3/dir4', 
    stderr=subprocess.STDOUT) 
except subprocess.CalledProcessError as problem: 
    print "Error", problem.returncode 
    print " while calling subprocess, output was:", problem.output 
else: 
    print "No error while calling subprocess, output was:", output 

我不得不提,這捕獲子進程的所有輸出,因此,如果這確實子很多,很多(也許永遠不會終止),這將填補你的RAM。在這種情況下,考慮使用check_call()而不是check_output(),也許將輸出重定向到/dev/null

-2
import os ,subprocess 
    os.chdir("dir3/dir4") 
    os.system("./wlst.sh") 

否則ü可以使用子

os.chdir("dir3/dir4") 
    subprocess.call("./wlst.sh") 
+0

使用'chdir'會產生明顯的副作用。 – Alfe 2013-03-27 14:57:14