繁体   English   中英

Python 3.4.3:os.system无法运行我的ping“命令”

[英]Python 3.4.3: os.system does not run my ping “command”

我制作了此脚本,只需单击它即可写出主机的IP或名称。...但是在python 3.4.3中,代码根本不运行ping; 我可以输入ip,但不能运行ping...。

我试图输入两种方式。 例如:“ 127.0.0.1”或127.0.0.1

它在python 2.7中运行,但希望它在python的更新版本中运行...

我的Windows是7 64位

您对我有什么建议/建议?

import os
a = input("put the name / ip of the machine you want to ping:\n\n")
p = "ping -t "
os.system(p+a)

我应该只使用运行良好的python 2.7吗???

python 2.7和python 3之间的input有所不同

在python 2中,它评估返回值,我敢打赌您在简单引号之间输入字符串。

在python 3中,它返回一个字符串(就像raw_input一样)

只要输入您的值不带引号,它将起作用。

Popen解决方案:

from subprocess import Popen, PIPE
p = Popen(['ping', '-c 1', 'www.google.com'], stdout=PIPE)
while True:
    line = p.stdout.readline()
    if not line:
        break
    print(line)

拆解解决方案:

import sh
for line in sh.ping('www.google.com', '-c 1', _err_to_out=True, _iter=True, _out_bufsize=100):
    print(line)

os.system解决方案:

import os
os.system('ping -c 1 www.google.com')

如果os.system()生成任何输出,它将被发送到解释器标准输出流。

我使用选项-c仅发送一个数据包。 要构造命令字符串,可以使用以下方法:

a = input("put the name / ip of the machine you want to ping:\n\n")
cmd = 'ping -c 1 %s' % a
os.system(cmd)

实际上,我放弃尝试了.....我将在运行良好的python 2.7中使用...。

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM