Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a python script from a python script

Tags:

python

I have a python script 'b.py' which prints out time ever 5 sec.

while (1):
   print "Start : %s" % time.ctime()
   time.sleep( 5 )
   print "End : %s" % time.ctime()
   time.sleep( 5 )

And in my a.py, I call b.py by:

def run_b():
        print "Calling run b"
    try:
        cmd = ["./b.py"]

        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        for line in iter(p.stdout.readline, b''):
                        print (">>>" + line.rstrip())


    except OSError as e:
        print >>sys.stderr, "fcs Execution failed:", e  

    return None  

and later on, I kill 'b.py' by: PS_PATH = "/usr/bin/ps -efW"

def kill_b(program):
    try:

        cmd = shlex.split(PS_PATH)

        retval = subprocess.check_output(cmd).rstrip()
        for line in retval.splitlines():

            if program in line:
                print "line =" + line
                pid = line.split(None)[1]
                os.kill(int(pid), signal.SIGKILL)

    except OSError as e:
        print >>sys.stderr, "kill_all Execution failed:", e
    except subprocess.CalledProcessError as e:
        print >>sys.stderr, "kill_all Execution failed:", e

run_b()
time.sleep(600)
kill_b("b.py")

I have 2 questions. 1. why I don't see any prints out from 'b.py' and when I do 'ps -efW' I don't see a process named 'b.py'? 2. Why when I kill a process like above, I see 'permission declined'?

I am running above script on cygwin under windows.

Thank you.

like image 358
michael Avatar asked Aug 21 '13 19:08

michael


1 Answers

  1. Why I don't see any prints out from 'b.py' and when I do 'ps -efW' I don't see a process named 'b.py'?

    Change run_b() lines:

    p = subprocess.Popen(cmd,
                         stdout=sys.stdout,
                         stderr=sys.stderr)
    

    You will not see a process named "b.py" but something like "python b.py" which is little different. You should use pid instead of name to find it (in your code "p.pid" has the pid).

  2. Why when I kill a process like above, I see 'permission declined'?

    os.kill is supported under Windows only 2.7+ and acts a little bit different than posix version. However you can use "p.pid". Best way to kill a process in a cross platform way is:

    if platform.system() == "Windows":
        subprocess.Popen("taskkill /F /T /PID %i" % p.pid, shell=True)
    else:
        os.killpg(p.pid, signal.SIGKILL)
    

killpg works also on OS X and other Unixy operating systems.

like image 56
J_Zar Avatar answered Sep 28 '22 11:09

J_Zar