How to terminate a python subprocess launched with shell=True

前端 未结 12 2745
轮回少年
轮回少年 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:03

    I have not seen this mentioned here, so I am putting it out there in case someone needs it. If all you want to do is to make sure that your subprocess terminates successfully, you could put it in a context manager. For example, I wanted my standard printer to print an out image and using the context manager ensured that the subprocess terminated.

    import subprocess
    
    with open(filename,'rb') as f:
        img=f.read()
    with subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE) as lpr:
        lpr.stdin.write(img)
    print('Printed image...')
    

    I believe this method is also cross-platform.

提交回复
热议问题