我想用这个ping -t www.google.com
命令运行一个python脚本文件。
到目前为止,我用ping www.google.com
命令做了一个工作,但我没有成功地继续使用ping -t
循环。
你可以在下面找到我的ping.py
脚本:
import subprocess
my_command="ping www.google.com"
my_process=subprocess.Popen(my_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result, error = my_process.communicate()
result = result.strip()
error = error.strip()
print ("\nResult of ping command\n")
print("-" *22)
print(result.decode('utf-8'))
print(error.decode('utf-8'))
print("-" *22)
input("Press Enter to finish...")
我希望命令框在完成后保持打开状态。我使用的是Python 3.7。
如果您希望保持进程打开并始终与其进行通信,则可以使用my_process.stdout作为输入,例如迭代它的线条。通过“沟通”,你等到过程完成,这对于无限期运行的过程是不利的:)
import subprocess
my_command=["ping", "www.google.com"]
my_process=subprocess.Popen(my_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
print( my_process.stdout.readline() )
编辑
在这个版本中,我们使用re只从输出中获取“time = xxms”部分:
import subprocess
import re
my_command=["ping", "-t", "www.google.com"]
my_process=subprocess.Popen(my_command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
while True:
line = my_process.stdout.readline() #read a line - one ping in this case
line = line.decode("utf-8") #decode the byte literal to string
line = re.sub("(?s).*?(time=.*ms).*", "\\1", line) #find time=xxms in the string and use only that
print(line)