[python]执行系统命令, os.system, subprocess.run, subprocess.Popen的示例

#从subprocess.py的代码中分析,subprocess.run是最好用的一个函数,既可以获取输出消息,也可以只执行command。

参考代码片段:

import os
import subprocess

###all in all, subprocess.run() is most powerful and easy to use


cmd = "py time_out_test.py"
time_out = 11
#######################################################################
'''
using os, it will not capture output message
'''

a = os.system(cmd) #it will return 0 if no error

#######################################################################
'''
using subprocess, it will capture output message
'''
#approach #1 --> suggest use this approach
#check from source code of subprocess.py, function run() is call the Popen() class
try:
    #cmd supports one list with command and parameter
    cmd=["py", "time_out_test.py"]
    p=subprocess.run(cmd, capture_output=True, timeout=time_out)
    ret_val = p.stdout
except subprocess.TimeoutExpired:
    print ("time out")


#approach #2
try:
    #cmd supports one list with command and parameter
    cmd=["py", "time_out_test.py", "para1", "para2"]
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = p.communicate(timeout=11)
    #p.wait(timeout=11)  #if use this function, it will not return output message
except subprocess.TimeoutExpired:
    print ("time out")

#######################################################################
'''
code in time_out_test.py:
import time

for i in range(10):
    time.sleep(1)
    print (i)
'''

你可能感兴趣的:(python,python)