【问题标题】:Python run command support realtime output, timeout and terminatePython 运行命令支持实时输出、超时和终止
【发布时间】:2019-06-24 07:02:16
【问题描述】:

想要一个Python函数可以运行shell命令,比如,

echo 'Process started'; ping 127.0.0.1 -i 2 ; echo 'Process finished'

要求,

  1. 它可以捕获实时输出,当命令完成时,它有一个返回值。
  2. 可以设置超时时间,超时时,该命令应该被杀死。

有人可以帮我解决这个问题吗?

Subprocess.run 看起来不起作用,原因是命令没有被杀死,仍在运行,

subprocess.run(cmd, stderr=sys.stderr, stdout=sys.stdout, shell=True, timeout=timeout)

【问题讨论】:

    标签: python


    【解决方案1】:

    实际上,subprocess.run 中的 timeout 选项应该会终止该命令。似乎this doesn't work when shell=True is also set. 如果您不需要高级 shell 功能,您可以随时将您的命令分解为参数,然后执行以下操作:

    subprocess.run(['ping', '127.0.0.1', '-i', '2'], timeout = 10)
    

    这还有一个优点是可以很容易地从 Python 中更改参数而不会导致安全问题。

    【讨论】:

    • 如果我去掉shel=True,我不能输入复杂的命令,例如“echo 'Process started'; ls /; echo 'Process finished'”,我使用的是shlex.split,它会搞砸命令。
    • 如果您真的想要 shell 语言的全部灵活性(和复杂性),请仔细考虑。如果你真的这样做,也许我链接的问题会对你有所帮助。
    【解决方案2】:

    我相信os.system() 会满足您的需求:-

    1. 它显示实时输出,就像你在运行命令一样 一个终端
    2. 当一个命令成功执行时,返回一个 代码(例如,如果命令成功则返回 0)
    3. 可以通过Control + C(键盘中断)中断。

    您给定的复合命令可以被剥离,以创建每个单独的命令,例如:-

    echo 'Process started'; ping 127.0.0.1 -i 2 ; echo 'Process finished'
    

    变成:-

    echo 'Process started'
    ping 127.0.0.1 -i 2
    echo 'Process finished'
    

    不,您可以将每个命令存储在单独的变量/列表中。然后将其传递给os.system()

    例子:-

    import os
    
    os.system("echo 'Process started'")
    os.system("ping 127.0.0.1 -i 2")
    os.system("echo 'Process Finished'")
    

    样本输出:-

    'Process started'
    
    Pinging 127.0.0.1 with 32 bytes of data:
    Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
    
    Ping statistics for 127.0.0.1:
        Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
    Approximate round trip times in milli-seconds:
        Minimum = 0ms, Maximum = 0ms, Average = 0ms
    'Process Finished'
    

    P.S.:- 对于您的情况,这只是 os.system() 的一个外行示例。您可以进一步将其扩展为故障安全版本。

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 2015-10-07
      相关资源
      最近更新 更多