使用如下的例子中的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import subprocess def execShellCommand(cmd): print cmd p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: buff = p.stdout.readline() if buff == '' and p.poll() != None: break print buff p.wait() def main(): execShellCommand("source ~/.profile") if __name__ == "__main__": main() |
运行的时候报告错误
1 2 |
source ~/.profile /bin/sh: 1: source: not found |
这个错误发生的原因是subprocess.Popen
执行Shell
命令的时候默认调用/bin/sh
,而source
命令/bin/bash
才支持的,因此导致错误发生,修改后的脚本如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import subprocess def execShellCommand(cmd): print cmd p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,executable="/bin/bash") while True: buff = p.stdout.readline() if buff == '' and p.poll() != None: break print buff p.wait() def main(): execShellCommand("source ~/.profile") if __name__ == "__main__": main() |
注意添加的executable="/bin/bash"
,指明了执行脚本的执行程序是/bin/bash
。