V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
not13
V2EX  ›  Python

subprocess.Popen 问题---初学者求解,问个弱智问题, 谢谢大家

  •  
  •   not13 · 2017-12-11 17:30:17 +08:00 · 3099 次点击
    这是一个创建于 2327 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import subprocess
    import re
    ping_waiting = "-w 1000";
    ping_cmd = "ping";
    ping_count_flag = "-n";
    
    def ping_host_once (host,c):
    	
      ping_count = " ".join([ping_count_flag,c])
    	cmd_line = " ".join([ping_cmd,ping_waiting,ping_count,host])
    	print(cmd_line)
    	sub = subprocess.Popen([ping_cmd,ping_waiting,ping_count,host],stdout=subprocess.PIPE)
    	#sub = subprocess.Popen(cmd_line,stdout=subprocess.PIPE)
    	output = sub.stdout.read().decode("gbk")
    	print (output)
    
    	
    a = ping_host_once("bai.com","5")
    

    上述代码运行结果如下

    D:\me>test2.py
    ping -w 1000 -n 5 bai.com
    
    正在 Ping bai.com [112.90.154.3] 具有 32 字节的数据:
    PING:传输失败。常见故障。
    PING:传输失败。常见故障。
    PING:传输失败。常见故障。
    PING:传输失败。常见故障。
    
    112.90.154.3 的 Ping 统计信息:
        数据包: 已发送 = 4,已接收 = 0,丢失 = 4 (100% 丢失),
    

    如果换成 sub = subprocess.Popen(cmd_line,stdout=subprocess.PIPE) 结果就是正常的。谁知道是什么原因啊。win10 环境。。。。。。。。

    D:\me>test2.py
    ping -w 1000 -n 5 bai.com
    
    正在 Ping bai.com [112.90.154.3] 具有 32 字节的数据:
    来自 112.90.154.3 的回复: 字节=32 时间=71ms TTL=48
    来自 112.90.154.3 的回复: 字节=32 时间=70ms TTL=48
    来自 112.90.154.3 的回复: 字节=32 时间=69ms TTL=48
    来自 112.90.154.3 的回复: 字节=32 时间=71ms TTL=48
    来自 112.90.154.3 的回复: 字节=32 时间=72ms TTL=48
    
    112.90.154.3 的 Ping 统计信息:
    数据包: 已发送 = 5,已接收 = 5,丢失 = 0 (0% 丢失),
    往返行程的估计时间(以毫秒为单位):
    最短 = 69ms,最长 = 72ms,平均 = 70ms
    
    4 条回复    2017-12-12 12:47:27 +08:00
    zk8802
        1
    zk8802  
       2017-12-11 19:03:58 +08:00 via iPhone
    楼主试一下把 -w、1000、-n、5 分成四个参数,而不是两个参数传给 Popen ?
    guyskk0x0
        2
    guyskk0x0  
       2017-12-11 20:08:33 +08:00 via Android
    文档里说 args 会转换成字符串再进行系统调用;命令中的空格和特殊符号可能会导致问题。
    264768502
        3
    264768502  
       2017-12-11 21:24:19 +08:00 via Android
    楼上都说完了

    试试这个 : https://pypi.python.org/pypi/pyping/ ?
    not13
        4
    not13  
    OP
       2017-12-12 12:47:27 +08:00
    谢谢各位,把 -w、1000、-n、5 分成四个参数,确实就没问题了,看来命令中的空格和特殊符号可能会导致问题。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1110 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:37 · PVG 06:37 · LAX 15:37 · JFK 18:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.