Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run an executable, wait for it to produce output, run another program

Within a Python script, I'm trying to execute the following sequence of events:

  1. Open a command window and run a program. When it completes, it outputs a text file.
  2. Once that text file has been created, close the program.
  3. After that has happened, run a new program using the text file as an input

Here's what I have so far:

subprocess.popen(['cmd','/c',r'programThatRuns.exe'])
subprocess.wait()  # ? subprocess.check_call()? kill?
subprocess.popen(['cmd','/c',r'otherProgramThatRuns.exe'])

So I guess I'm really stuck on the second line

like image 654
PHiL Avatar asked Oct 14 '25 03:10

PHiL


2 Answers

I think all you need is:

subprocess.check_call(['programThatRuns.exe'])
subprocess.check_call(['otherProgramThatRuns.exe'])

The check_call function will run the program and wait for it to finish. If it fails (non-0 exit code) it will throw a CalledProcessError exception.

You generally don't want to run programs through cmd, just run them directly. You only need to force using cmd if the program isn't an executable, e.g. for a builtin command like dir, for a .bat or .cmd file, or if you want to use file associations.

like image 105
Duncan Avatar answered Oct 16 '25 15:10

Duncan


Have you tried using subprocess.call?

Python 2 - Python 3

Run the command described by args. Wait for command to complete, then return the returncode attribute.

Seems to be what you're trying to do. Simply run the first process, check that the file exists, and pass the file into the second process to use.

subprocess.check_call will also work for what you're trying to do, except that if the process returns a non-zero return code it'll raise an exception while call will simply return the return code.

like image 32
David Reeve Avatar answered Oct 16 '25 15:10

David Reeve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!