在python程序中执行linux命令

时间:2013-03-27 14:25:44

标签: python subprocess

我正在linux中编写一个python程序。

在我的python程序中,我需要在python程序本身内的另一个工作目录中执行linux命令。

实施例: 我的程序test.py位于目录dir1 / dir2。

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

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

如何做到这一点?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

答案 2 :(得分:-2)

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

或者你可以使用子流程

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