如何从python脚本调用python脚本

时间:2013-08-21 19:56:51

标签: python

我有一个python脚本'b.py',打印时间为5秒。

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

在我的a.py中,我通过以下方式调用b.py:

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  

以后,我通过以下方式杀死'b.py':     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")

我有2个问题。 1.为什么我看不到'b.py'中的任何打印件,当我'ps -efW'时,我没有看到名为'b.py'的过程? 2.为什么当我杀死上述过程时,我看到“许可拒绝了”?

我在windows下的cygwin上运行脚本。

谢谢。

1 个答案:

答案 0 :(得分:1)

  1. 为什么我从'b.py'看不到任何打印件,当我'ps -efW'时,我没有看到名为'b.py'的进程?

    更改run_b()行:

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

    你不会看到一个名为“b.py”的进程,但是像“python b.py”这样的进程稍有不同。您应该使用pid而不是name来查找它(在您的代码“p.pid”中有pid)。

  2. 为什么当我杀死上述过程时,我看到“许可被拒绝了”?

    Windows支持的os.kill只有2.7+,与posix版本略有不同。但是你可以使用“p.pid”。以跨平台方式终止进程的最佳方法是:

    if platform.system() == "Windows":
        subprocess.Popen("taskkill /F /T /PID %i" % p.pid, shell=True)
    else:
        os.killpg(p.pid, signal.SIGKILL)
    
  3. killpg也适用于OS X和其他Unixy操作系统。