[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)
'''

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值