6

I need to execute two other python scripts from another one. commands look like this:

# python send.py

# python wait.py

This will happen in a loop that will sleep for 1 minute then re-run.

Before executing the commands to start the other scripts I need to make sure they are not still running.

5
  • Have you tried using the subprocess module? Commented Sep 26, 2012 at 15:30
  • 1
    Why can't you import the two scripts and call the functions inside of them normally? Commented Sep 26, 2012 at 15:31
  • Because the two apps will be rewritten in a different language at some point. Commented Sep 26, 2012 at 15:34
  • subprocess seems to wait for the application to finish before continuing. I need to just execute and move on. Commented Sep 26, 2012 at 15:37
  • @larsmans, it does, if you do not explictly use Popen. Commented Sep 28, 2012 at 14:46

2 Answers 2

21

You can use subprocess.Popen to do that, example:

import subprocess

command1 = subprocess.Popen(['command1', 'args1', 'arg2'])
command2 = subprocess.Popen(['command2', 'args1', 'arg2'])

if you need to retrieve the output do the following:

command1.wait()
print command1.stdout

Example run:

sleep = subprocess.Popen(['sleep', '60'])
sleep.wait()
print sleep.stdout  # sleep outputs nothing but...
print sleep.returncode  # you get the exit value
Sign up to request clarification or add additional context in comments.

1 Comment

stdout is only meaningful when stdout=subprocess.PIPE is passed to the Popen constructor.
1
import time
import commands
from subprocess import Popen

while True:
  t_ph = commands.getstatusoutput('ps -eo pid,args | grep script1.py | grep -v service | grep -v init.d | grep -v grep | cut -c1-6')
  t_fb = commands.getstatusoutput('ps -eo pid,args | grep script2.py | grep -v service | grep -v init.d | grep -v grep | cut -c1-6')

  if t_ph[1] == '':
    r_ph = Popen(["python", "script1.py"])

  if t_fb[1] == '':
    r_fb = Popen(["python", "script2.py"])

  time.sleep(60)

or

import time
import commands
from subprocess import Popen

r_ph = False
r_fb = False

while True:

  if r_ph == False:
    r_ph = Popen(["python", "script1.py"])
  else:
    if r_ph.poll():
      r_ph = Popen(["python", "script1.py"])

  if r_fb == False:
    r_fb = Popen(["python", "script2.py"])
  else:
    if r_fb.poll():
      r_fb = Popen(["python", "script2.py"])

  time.sleep(60)

this could be written a bit better but it works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.