Matze
Matze

Reputation: 3

Python subprocess command don't wait if multiple instances are active

I used some code for several months, where I open a browser with a specific webpage. Through this webpage I can access the frontend of a database, where I can filter some data and export them to a .txt file. After closing the browser, my python code will continue, working with the data, which were exported before.

Today I had the problem, that the browser was opened and the python code didn't wait until the browser was closed, but instantly ran on and did nothing, because the file (where the exported data will be saved) was still empty.

Until now I open the browser with (URL is a replacement):

browser = r'C:\Program Files\Internet Explorer\iexplore.exe'
url = r'https://www.google.com' 
command = r'{browser} "{url}"'.format(browser=browser, url=url)
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()

After I searched for this error on some webpages, I changed it from subprocess.Popen to subprocess.run:

process = subprocess.run(command, capture_output=True, text=True)
output = process.stdout
error = process.stderr
returncode = process.returncode

But this didn't worked either.

Then by chance I noticed that another browser session was running in the background. As I closed this session, the code was running like before, stopping and waiting until the browser was closed. As soon as another session of the browser was already running, the code didn't work anymore and continued until the end.

I have now helped myself by inserting an input("Press Enter to continue...") after the subprocess call to be sure that the code will stop the execution until the file with the data is written, but this should be a temporary solution at most.

I did not find anything about this strange behavior. Did I something wrong? How can I handle this problem?

Upvotes: 0

Views: 315

Answers (1)

tripleee
tripleee

Reputation: 189377

The problem is on the Internet Explorer side. IE (and I believe generally any browser) will notice that a browser process is already running, and the subprocess will finish as soon as it dispatches the event to the running browser to visit the URL you wanted to open.

The switch to subprocess.run() is correct as such, but not sufficient. Maybe find a way to block if iexplorer.exe is already running, or run a different (and by any reasonable metric better) browser instead when that happens.

As an aside, assembling the command into a string is both unnecessary and potentially problematic here. The difference is not that great on Windows, but you should still understand it.

process = subprocess.run([browser, url], capture_output=True, text=True)

Upvotes: 1

Related Questions