【问题标题】:wait for terminal command to finish in python等待终端命令在python中完成
【发布时间】:2018-05-16 19:11:34
【问题描述】:

我有一个可以使用终端运行的 python 脚本。但是,我需要等到它完成(输出两个文本文件)才能继续。我实现了:

command=['python','segment.py','audio.wav','trans.txt','out1.txt','out2.txt']
cmd=subprocess.Popen(command).wait()

它确实会立即生成 out1.txt 和 out2.txt,但它们是空的。当我从终端运行命令时,我得到了正确的 out1.txt 和 out2.txt(几分钟后)。我应该使用其他一些操作命令吗?

【问题讨论】:

    标签: python command-line terminal


    【解决方案1】:

    尝试使用os.system。这将等待命令完成,如果运行成功则返回退出状态 0。要获取其他退出状态的含义,请使用os.strerror(exit_status)

    请参阅 https://docs.python.org/3.5/library/os.html#os.systemhttps://docs.python.org/3.5/library/os.html#os.strerror 以获得更多帮助。

    例子:

    os.system('python segment.py audio.wav trans.txt out1.txt out2.txt')
    >>> 0
    

    请注意os.system 的参数必须是str 类型。

    【讨论】:

      【解决方案2】:

      使用交流:

      cmd = subprocess.Popen(command)
      cmd.communicate()
      # Code to be run after execution finished
      

      【讨论】:

        猜你喜欢
        • 2011-10-20
        • 1970-01-01
        • 2012-06-07
        • 2013-04-03
        • 2015-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-20
        相关资源
        最近更新 更多