目录
subprocess.call()
res = subprocess.call('ls -l', shell = True)
print 'res:', res
subprocess.check_out()
import subprocess
try:
res = subprocess.check_call(['ls', '('])
print 'res:', res
except subprocess.CalledProcessError, exc:
print 'returncode:', exc.returncode
print 'cmd:', exc.cmd
print 'output:', exc.output
subprocess.check_output()
import subprocess
try:
res = subprocess.check_output('ls xxx',
stderr = subprocess.STDOUT,
shell = True)
print 'res:', res
except subprocess.CalledProcessError, exc:
print 'returncode:', exc.returncode
print 'cmd:', exc.cmd
print 'output:', exc.output
subprocess.Popen()
阻塞问题:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import subprocess
from threading import Timer
import os
class test(object):
def __init__(self):
self.stdout = []
self.stderr = []
self.timeout = 10
self.is_timeout = False
pass
def timeout_callback(self, p):
self.is_timeout = True
print 'exe time out call back'
print p.pid
try:
os.killpg(p.pid, signal.SIGKILL)
except Exception as error:
print error
def run(self):
cmd = ['bash', '/home/zhangxin/work/baofabu/test.sh']
#p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid)
my_timer = Timer(self.timeout, self.timeout_callback, [p])
my_timer.start()
try:
print "start to count timeout; timeout set to be %d \n" % (self.timeout,)
for line in iter(p.stdout.readline, b''):
print line
if self.is_timeout:
break
for line in iter(p.stderr.readline, b''):
print line
if self.is_timeout:
break
finally:
my_timer.cancel()
p.stdout.close()
p.stderr.close()
p.kill()
p.wait()
其中test.sh:
#!/bin/bash
ping www.baidu.com
echo $$
像threading那样执行python函数:
import os
import signal
import subprocess
import tempfile
import time
import sys
def show_setting_prgrp():
print('Calling os.setpgrp() from {}'.format(os.getpid()))
os.setpgrp()
print('Process group is now {}'.format(
os.getpid(), os.getpgrp()))
sys.stdout.flush()
# 这次的重点关注是这里
script = '''#!/bin/sh
echo "Shell script in process $$"
set -x
python signal_child.py
'''
script_file = tempfile.NamedTemporaryFile('wt')
script_file.write(script)
script_file.flush()
proc = subprocess.Popen(
['sh', script_file.name],
preexec_fn=show_setting_prgrp,
)
print('PARENT : Pausing before signaling {}...'.format(
proc.pid))
sys.stdout.flush()
time.sleep(1)
print('PARENT : Signaling process group {}'.format(
proc.pid))
sys.stdout.flush()
os.killpg(proc.pid, signal.SIGUSR1)
time.sleep(3)
本文深入探讨了Python中使用subprocess模块管理子进程的方法,包括call、check_call、check_output及Popen函数的详细应用。通过实例展示了如何处理子进程的输出、错误以及超时情况,特别关注了Popen在复杂场景下的阻塞问题解决方案。
1769

被折叠的 条评论
为什么被折叠?



