执行Linux命令并获取PID

Ben*_*Ben 0 python linux

通常我使用:

os.popen("du folder >> 1.txt ").read()
Run Code Online (Sandbox Code Playgroud)

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

os.popen("du folder >> 1.txt &").read() # Notice the & symbol
Run Code Online (Sandbox Code Playgroud)

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

AKX*_*AKX 7

你会想要使用该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()
Run Code Online (Sandbox Code Playgroud)