Ubuntu 14.04系统上Python使用"subprocess.Popen"执行"source"命令报告错误“/bin/sh: source: not found”

使用如下的例子中的代码

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()

运行的时候报告错误

source ~/.profile
/bin/sh: 1: source: not found

这个错误发生的原因是subprocess.Popen执行Shell命令的时候默认调用/bin/sh,而source命令/bin/bash才支持的,因此导致错误发生,修改后的脚本如下:

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

参考链接


Calling the “source” command from subprocess.Popen

发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注