Python3 subprocess

2021-12-16  本文已影响0人  逍遥_yjz
import subprocess
def testMingLing(cmd):
    subp = subprocess.Popen(cmd,
                        shell=True,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        encoding="utf-8")
    subp.wait(2)
    print(subp.pid)
    print(subp.stdout.readlines())
    #print(subp.stderr)
    if subp.poll() == 0:
        print(123)
        print(subp.communicate()[1])
    else:
        print("失败")

if __name__ == '__main__':
    cmd = 'cd ../oneCX;nohup python3 writeFile.py fenfa > fenfa.log &'
    testMingLing(cmd)

import subprocess
def runcmd(command):
    ret = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
    if ret.returncode == 0:
        print("success:",ret)
    else:
        print("error:",ret)


runcmd(["dir","/b"])#序列参数
runcmd("exit 1")#字符串参数

总结:

实战实例

import subprocess
def main(exec_command):
    # exec_command = 'python cloudChart_crond.py  -k 01 001'
    # exec_command = 'python cloudChart_crond.py  -k 05'
    p = subprocess.Popen(exec_command,
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     encoding="utf-8")

    for line in p.stdout.readlines():
        print(line.strip())
        print('----------------')
    etval = p.wait()
    if etval == 0:
        print('===========================成功===========================')
上一篇 下一篇

猜你喜欢

热点阅读