How to terminate a python subprocess launched with shell=True

前端 未结 12 2703
轮回少年
轮回少年 2020-11-21 04:53

I\'m launching a subprocess with the following command:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

However, when I try t

12条回答
  •  不知归路
    2020-11-21 05:14

    Although it is an old question, it has a high google rank. so I decided to post an answer with the new method someone can use in python 3 to manage this easily and with confidence. as of python 3.5 you there is a new method added to subprocess package called run().

    As the documentation says:

    It is the recommended approach to invoking sub processes for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

    The subprocess.run():

    Runs a command described by args. Wait for the command to complete, then return a CompletedProcess instance.

    for example one can run this snippet within a python console:

    >>> subprocess.run(["ls", "-l"])  # doesn't capture output
    CompletedProcess(args=['ls', '-l'], returncode=0)
    

    P.S. In case of the OP's specific question, I wasn't able to reproduce his problem. commands I run with popen() are terminating properly.

提交回复
热议问题