Python创建子进程, 执行 'ping ....',判断运行结果

来源:互联网 发布:网络劫持是什么意思 编辑:程序博客网 时间:2024/06/15 22:02

创建一个新的子进程, 执行 ‘ping 192.168.0.102’,等待子进程结束后或者等待时间到达后,读取子进程的返回值和子进程的标准输出,判断子进程是否正常退出和标准输出中是否有‘timed out’ 然后给全局变量FREEMV_INTERACT_RESULT赋值。

import timeimport threadingimport osimport subprocesstaskkill = os.getenv('SYSTEMROOT')+'/System32/taskkill.exe'def interact_run(cmd,timeout=2):    def timeout_trigger(sub_process):        print 'timeout function trigger'        os.system(taskkill+' /T /F /pid '+ str(sub_process.pid))    timeout = float(timeout)    p = subprocess.Popen(cmd, 0, None, None, subprocess.PIPE, subprocess.PIPE,shell=True)    t = threading.Timer(timeout*60, timeout_trigger, args=(p,))    t.start()    p.wait()    t.cancel()    ret_val = p.returncode    ret_info = p.stdout.read()    return ret_val,ret_infotime.sleep(5)ret = interact_run('ping 192.168.0.102')if ret[0] == 0 and ('timed out' not in ret[1]):    FREEMV_INTERACT_RESULT = 0else:    FREEMV_INTERACT_RESULT = 1

1.
p = subprocess.Popen(cmd, 0, None, None, subprocess.PIPE, subprocess.PIPE,shell=True)

详解
http://www.cnblogs.com/fengbeihong/articles/3374132.html
subprocess.Popen
subprocess模块定义了一个类: Popen
class subprocess.Popen( args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0)
这里写图片描述

详解
subprocess.PIPE实际上为文本流提供一个缓存区。
我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe)。
http://www.jb51.net/article/66440.htm

2.
import threading
t = threading.Timer(timeout*60, timeout_trigger, args=(p,))

详解
python通过线程实现定时器timer的方法.
让系统定时执行指定的函数.

3.
t.start()

详解
run方法 和start方法: 它们都是从Thread继承而来的.
run()方法将在线程开启后执行,可以把相关的逻辑写到run方法中(通常把run方法称为活动[Activity]。);
start()方法用于启动线程。

p.wait()
详解
Popen.wait()
等待子进程结束。设置并返回returncode属性。

4.
Python的调试方法pdb

启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。
python -m pdb err.py
以参数-m pdb启动后,pdb定位到下一步要执行的代码。

输入命令l来查看代码。
输入命令n可以单步执行代码。
任何时候都可以输入命令p 变量名来查看变量。
输入命令q结束调试,退出程序。
http://www.jb51.net/article/65072.htm

5.
ret_val = p.returncode
ret_info = p.stdout.read()
return ret_val,ret_info

if ret[0] == 0 and (‘timed out’ not in ret[1]):
FREEMV_INTERACT_RESULT = 0
else:
FREEMV_INTERACT_RESULT = 1

详解
Popen.returncode
获取进程的返回值。如果进程还没有结束,返回None。

上面代码的意思是:
如果子进程的返回值为0,同时在标准输出中没有’timed out’这个的文字log,给FREEMV_INTERACT_RESULT 这个变量赋值为 0 。 其余情况下赋值为1 。

0 0
原创粉丝点击