python - Run subprocess with several commands and detach to background keeping order -


i'm using subprocess module execute 2 commands:

import shlex     subprocess import check_call()  def comm_1(error_file):     comm = shlex("mkdir /tmp/kde")     try:         check_call(comm)     except subprocess.calledprocesserror:         error_file.write("error comm_1")  def comm_2(error_file):     comm = shlex("ls -la /tmp/kde")     try:         check_call(comm)     except subprocess.calledprocesserror:         error_file.write("error comm_2")  if __name__ == "__main__":     open("error_file", "r+") log_error_file:          comm_1(log_error_file)          comm_2(log_error_file)          log_error_file.write("success") 

i'm aware of few pitfalls in design, error_file being shared functions. refactored, though. i'm trying detach entire process background. accomplish

 check_call(comm, creationflags=subprocess.create_new_console) 

but pose race problem, because want make sure comm_1 finished before comm_2 starts. best approach subprocess? can't use python-daemon or other packages outside standard python 2.6 library.

edit: try use like

nohup python myscript.py & 

but ideia have 1 way start job python script.

you can check make sure process inside of comm_1 dies before starting subprocess call within comm_2 using wait(). so, you're going have use popen() instead of check_call().

from subprocess import popen  def comm_1(error_file):     comm = shlex("mkdir /tmp/kde")     try:         proc_1 = popen(comm)         proc_1.wait(timeout=20)     except subprocess.calledprocesserror, timeoutexpired:         error_file.write("error comm_1") 

proc_1.wait() going wait 20 seconds (you can change time) process finish before continuing. if takes longer 20 secs, it's going throw timeoutexpired exception, can catch in except block.


Comments