How to start a background process in Python?

后端 未结 7 571
庸人自扰
庸人自扰 2020-11-22 02:44

I\'m trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background

相关标签:
7条回答
  • 2020-11-22 03:21

    While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.

    Example for your case:

    import subprocess
    subprocess.Popen(["rm","-r","some.file"])
    

    This will run rm -r some.file in the background. Note that calling .communicate() on the object returned from Popen will block until it completes, so don't do that if you want it to run in the background:

    import subprocess
    ls_output=subprocess.Popen(["sleep", "30"])
    ls_output.communicate()  # Will block for 30 seconds
    

    See the documentation here.

    Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.

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