在python中运行shell命令

2024-04-27 04:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个运行shell脚本的简单代码,它有时工作,有时工作不,如果不工作的控制台日志是:

Please edit the vars script to reflect your configuration, then source it with "source ./vars". Next, to start with a fresh PKI configuration and to delete any previous certificates and keys, run "./clean-all". Finally, you can run this tool (pkitool) to build certificates/keys.

这对我来说很奇怪,因为当我在控制台中运行命令时,它们会正常工作

def cmds(*args):

    cd1 = "cd /etc/openvpn/easy-rsa && source ./vars"
    cd2 = "cd /etc/openvpn/easy-rsa && ./clean-all"
    cd3  = "cd /etc/openvpn/easy-rsa && printf '\n\n\n\n\n\n\n\n\n' | ./build-ca"

    runcd1 = subprocess.Popen(cd1, shell=True)
    runcd2 = subprocess.Popen(cd2 , shell=True)
    runcd3 = subprocess.Popen(cd3 , shell=True)

    return (runcd1, runcd2, runcd3)  

我变成这样了:

def pass3Cmds(*args):
    commands = "cd /etc/openvpn/easy-rsa && source ./vars && ./clean-all &&   printf '\n\n\n\n\n\n\n\n\n' | ./build-ca"
    runCommands = subprocess.Popen(commands, shell=True, stdout=PIPE)
    return (runCommands)

但控制台写下:

source: not found


Tags: tobuildcleantruesourceeasyetccd
1条回答
网友
1楼 · 发布于 2024-04-27 04:11:13

您需要将这三个命令合并为一个命令。你知道吗

“source./vars”只影响从中运行它的shell。当您使用三个单独的Popen命令时,您将得到三个单独的shell。你知道吗

在一个Popen中运行所有命令,命令之间有&;s。你知道吗

这种方法之所以“有时”能像编写的那样工作,是因为有时您在shell中运行python,而您已经在shell中获取了vars脚本。你知道吗

相关问题 更多 >