user552231
user552231

Reputation: 1135

wait for terminal command to finish in python

I have a python script that I can run using the terminal. However, I need to wait until it finishes (outputs two text files) before I can continue. I implemented:

command=['python','segment.py','audio.wav','trans.txt','out1.txt','out2.txt']
cmd=subprocess.Popen(command).wait()

it does generate out1.txt and out2.txt almost immideatly but they are empty. When I run the command from the terminal I get the correct out1.txt and out2.txt (after a few minutes). Should I use some other operating commands?

Upvotes: 3

Views: 8698

Answers (2)

user8202635
user8202635

Reputation:

Try using os.system. This will wait for the command to finish, and returns the exit status of 0 if it runs successfully. To get the meaning of other exit statuses, use os.strerror(exit_status).

See https://docs.python.org/3.5/library/os.html#os.system and https://docs.python.org/3.5/library/os.html#os.strerror for more help.

Example:

os.system('python segment.py audio.wav trans.txt out1.txt out2.txt')
>>> 0

Please note that the argument for os.system must be of type str.

Upvotes: 1

Evya
Evya

Reputation: 2375

use communicate:

cmd = subprocess.Popen(command)
cmd.communicate()
# Code to be run after execution finished

Upvotes: 1

Related Questions