我正在linux中编写python程序。在python程序中执行linux命令
在我的python程序中,我需要在python程序本身的另一个工作目录中执行一个linux命令。
示例: 我的程序test.py位于目录dir1/dir2中。
./wlst.sh是dir1/dir2/dir3/dir4中的程序。
所以我需要在位于dir2的python程序的dir4中执行.wlst.sh。
这怎么办?
我正在linux中编写python程序。在python程序中执行linux命令
在我的python程序中,我需要在python程序本身的另一个工作目录中执行一个linux命令。
示例: 我的程序test.py位于目录dir1/dir2中。
./wlst.sh是dir1/dir2/dir3/dir4中的程序。
所以我需要在位于dir2的python程序的dir4中执行.wlst.sh。
这怎么办?
import subprocess
subprocess.call(['./wlst.sh'], cwd='dir1/dir2/dir3/dir4')
使用'chdir'会产生明显的副作用; call()'更好地使用可选参数'cwd ='。 – Alfe 2013-03-27 14:51:59
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
。
import os ,subprocess
os.chdir("dir3/dir4")
os.system("./wlst.sh")
否则ü可以使用子
os.chdir("dir3/dir4")
subprocess.call("./wlst.sh")
使用'chdir'会产生明显的副作用。 – Alfe 2013-03-27 14:57:14
我假设你用Google搜索,发现['subprocess'](http://docs.python.org/2/library/subprocess.html #module-subprocess)模块。你有什么问题? – 2013-03-27 14:29:36