执行Linux命令并获取PID

时间:2013-10-03 06:16:04

标签: python linux

通常我会使用:

os.popen("du folder >> 1.txt ").read()

工作正常。
但是当我想获取子进程id时,它返回空值。

os.popen("du folder >> 1.txt &").read() # Notice the & symbol

有谁知道为什么以及如何获得PID?

2 个答案:

答案 0 :(得分:6)

您需要使用subprocess模块。

# Can't use shell=True if you want the pid of `du`, not the
# shell, so we have to do the redirection to file ourselves
proc = subprocess.Popen("/usr/bin/du folder", stdout=file("1.txt", "ab"))
print "PID:", proc.pid
print "Return code:", proc.wait()

答案 1 :(得分:0)

&将进程置于后台和作业号!= pid。为了得到你的过程的pid。

我建议使用subprocess - Popen实例具有您可以直接访问的属性pid

相关问题