- 论坛徽章:
- 0
|
本帖最后由 jwshxyd 于 2013-08-30 13:52 编辑
一段简单的代码,可测试本机与指定地址ip的主机的连通性
import os,sys,re
import subprocess
num=int(input('Enter an Integer:'))
#ip=str(input('Enter ip:'))
for i in range(1,3):
ret=subprocess.call('ping 192.168.4.%d -n %d ' %(i,num),shell = True,stdout=open(r'D:\test_case\iptmp.txt','w'), stderr=subprocess.STDOUT)
if ret == 0:
print ("%d: is alive" % i)
else:
print ("%d is down" % i)
以上subprocess.call测试结果 4.1 ,4.2是可通的,4.2应该是不通的,但是代码运行结果显示都是 alive的,为何呢?
1 is alive
2 is alive
如果subprocess.Popen测试4.1,4.2都是不通的了
1 is down
2 is down
看来是返回的值不一样
查了下官方文档,看起来有点累,大致意思是 python3 的子进程模块subprocess 的存在是为了替换旧有的os.system,os.spawn* 等
subprocess.call
subprocess.call (*popenargs , **kwargs )
执行命令,并等待命令结束,再返回子进程的返回值。可查看/python33/Lib/subprocess.py
call(def call():) 是这样的:
def call(*popenargs, timeout=None, **kwargs):
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
关于Popen(class Popen(object) 的用法
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)
他们的返回值有何区别呢
|
|