-1

I am trying to make my Python code to start a .bat file, which in turn starts a .exe file. After the process had been launched, I want to wait for a certain amount of time before terminating the .exe process.

However, it seems like any code past the subprocess.call command that starts .bat file is not being executed.

Here is the code I have so far:

print("About to launch OTB!")

subprocess.call(
    ".\olympian.bat",
    cwd=str(Path(os.path.abspath(__file__)).parent.parent),
    shell=True,
)

print("About to sleep")

time.sleep(time_var)

print("Sleep over, will close OTB now!")

subprocess.call("taskkill /F /im olympian.exe")

print("OTB has been closed!")

The program does launch the olympian.bat process, however it does not display "About to sleep" message afterward.

Also, the olympian.exe program supposed to run infinitely long, unless I forcefully close it (with taskkill command in my case).

Let me know if you need more info, or you know of any way to elegantly make it work. Thanks!

TimesAndPlaces
  • 510
  • 1
  • 4
  • 20
  • 1
    From the docs for `subprocess.call`: "Run the command described by args. __Wait for command to complete__, then return the returncode attribute." https://docs.python.org/3/library/subprocess.html#subprocess.call – Iain Shelvington Jan 04 '20 at 23:45
  • @IainShelvington Alright, so, how would I make it to not wait for the launched process to complete before running the next line of my code? Many thanks! – TimesAndPlaces Jan 04 '20 at 23:47

1 Answers1

1

From the python docs, subprocess.call will run the command described by args. Wait for command to complete, then return the returncode attribute.

Since this will be running infinitely (until you kill it), the next line of code will never complete. You could instead use subprocess.Popen

More information on this process can be found in the docs.

Evan Edwards
  • 182
  • 11
  • So, how exactly can I use Popen to have the process running on the background while my code is being executed? I have already checked the docs, but couldn't find a direct answer to my question. – TimesAndPlaces Jan 05 '20 at 00:00
  • @TimesAndPlaces I found a similar SO question where someone else had the same issue. You can view it [here](https://stackoverflow.com/questions/10965949/can-subprocess-call-be-invoked-without-waiting-for-process-to-finish) – Evan Edwards Jan 05 '20 at 00:02
  • @TimesAndPlacesL You can call the `Popen` class instance's `poll()` method to see if it has completed. Read the [documentation](https://docs.python.org/3/library/subprocess.html#popen-objects). – martineau Jan 05 '20 at 00:48