Run another program and leave it running when the script ends

I'm using subprocess.Popen to run an external program with arguments, but when I open it, the script hangs, waiting for the program to finish, and if I close the script, the program exits immediately.

I thought I was just using a similar process before without issue, so I'm not sure if I really did it wrong or if I misunderstand what Popen can do. This is how I call my command:

    subprocess.Popen(["rv", rvFile, '-nc'])
    raw_input("= Opened file")

      

The raw_input part is only present there, so the user can see the message and know that the file should be opened. But what I get is all the information that the process itself spills out as if it were called directly on the command line. I figured out that Popen made it an independent child process that would allow me to close the script and keep the process open.

The linked duplicate question has a helpful answer for my purposes, although it still doesn't work the way I want it to.

This is the answer. And this is how I changed my code:

DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen(["rv", rvFile, '-nc'], creationflags=DETACHED_PROCESS).pid
raw_input("= Opened file")

      

It works from IDLE, but not when I run the py file through the command line style interface. It is still attached to that window, printing out the output and exiting the program as soon as I run the script.

+3


source to share


3 answers


This is specifically for running a python script as a command line process, but I ended up getting this working by combining the two answers people suggested.

Using the DETACHED_PROCESS combination suggested in this answer worked to run it through IDLE, but the command line interface. But using shell = True (as ajsp suggested) and the DETACHED_PROCESS parameter, it allows you to close the python script window and leave another program still running.



DETACHED_PROCESS = 0x00000008
pid = subprocess.Popen(["rv", rvFile, '-nc'], creationflags=DETACHED_PROCESS, shell=True).pid
raw_input("= Opened file")

      

0


source


The stackoverflow question Calling an external command in python has many helpful answers.

Take a look at os.spawnl

, it can accept multiple mode flags, which include NOWAIT, WAIT.



import os
os.spawnl(os.P_NOWAIT, 'some command')

      

The NOWAIT option will return the process ID of the child task.

+1


source


Sorry for such a short answer, but I have not yet received enough points to leave comments. Anyway, put it raw_input("= Opened file")

inside the file you are opening, not from the program from which you open it.

If the file you open is not a python file, it is closed upon completion, no matter what you declare from python. If so, you can always try to detach it from the parent using:

from subprocess import Popen, CREATE_NEW_PROCESS_GROUP
subprocess.Popen(["rv", rvFile, '-nc'], close_fds = True | CREATE_NEW_PROCESS_GROUP)

      

+1


source







All Articles