要在Python中运行命令并实时打印输出,可以使用subprocess模块。以下是一个示例代码:

import subprocess

# 定义命令
command = "ping 1.1.1.1"

# 使用subprocess.Popen运行命令
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)

# 实时打印输出
while True:
    output = process.stdout.readline().decode()  # 读取输出并转换为字符串
    if output == '' and process.poll() is not None:  # 没有输出且进程已结束
        break
    if output:  # 输出不为空
        print(output.strip())  # 打印输出的内容

这段代码将会运行ping 1.1.1.1命令,并实时打印输出。

用python运行一段命令ping 1111并实时打印其输出

原文地址: https://www.cveoy.top/t/topic/iSum 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录