简体   繁体   中英

How to tell Python to wait until a Windows command from os.system() finishes?

I want to execute a command in cmd to run Matlab in -nodesktop mode (so without gui). The Matlab program that I will run will create a .txt file that later in the same script pandas is going to parse. But on my Windows 10 (on Linux it works), pandas doesn't wait for the command to finish and tries to parse an empty file which results in this error:

pandas.errors.EmptyDataError: No columns to parse from file

This is the command that I run (with a couple (correct) function calls later in Matlab:

matlab -nodesktop -r

The whole string of commands is then run like this:

os.system(COMMAND_START)

A few lines later I try to parse the file with pandas , but it doesn't wait for the os.system() to finish, so right after the Matlab command starts (and it takes quite a long time for it to finish) pandas wants to parse an empty file. How can I make my script wait for the os.system() to finish?

df = pd.read_csv("stabs.txt", header=None)
STABS_KG = df[0].to_list()
STABS_1_KG = df[1].to_list()

If you don't want to complicate with the subprocess module and you have an estimate for the time it takes to finish, you could simply add a sleep(seconds) after the call:

os.system(COMMAND_START)
sleep(2) -> wait 2 seconds

You can also use the subprocess module:

import subprocess
process = subprocess.Popen(['COMMAND_START'])
exitCode=process.wait()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM