Python subprocess: wait for command to finish before starting next one?

前端 未结 2 441

I\'ve written a Python script that downloads and converts many images, using wget and then ImageMagick via chainedsubprocess calls:

for img in          


        
相关标签:
2条回答
  • 2021-01-05 00:06

    See Using module 'subprocess' with timeout

    Not sure if this is the proper way of doing it, but this is how I accomplish this:

    import subprocess
    from threading import Thread
    
    def call_subprocess(cmd):
        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = proc.communicate()
        if err:
            print err
    
    thread = Thread(target=call_subprocess, args=[cmd])
    thread.start()
    thread.join() # waits for completion.
    
    0 讨论(0)
  • 2021-01-05 00:13

    Normally, subprocess.call is blocking.

    If you want non blocking behavior, you will use subprocess.Popen. In that case, you have to explicitly use Popen.wait to wait for the process to terminate.

    See https://stackoverflow.com/a/2837319/2363712


    BTW, in shell, if you wish to chain process you should use && instead of ; -- thus preventing the second command to be launched if the first one failed. In addition, you should test the subprocess exit status in your Python program in order to determine if the command was successful or not.

    0 讨论(0)
提交回复
热议问题