【问题标题】:Execute Linux Command and Get PID执行 Linux 命令并获取 PID
【发布时间】:2013-10-03 06:16:04
【问题描述】:

我通常使用:

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

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

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

有人知道为什么以及如何获取 PID 吗?

【问题讨论】:

    标签: python linux


    【解决方案1】:

    您需要使用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()
    

    【讨论】:

    • 我在python 2.7下试过你的代码,它总是弹出一些错误:文件“/home/ben/qiime_software/python-2.7.3-release/lib/python2.7/subprocess.py”,第 1249 行,在 _execute_child raise child_exception OSError: [Errno 2] No such file or directory
    • 您的du 命令可能在其他地方。试试which du 看看在哪里。
    【解决方案2】:

    & 将进程置于后台,作业号 != pid。获取进程的 pid。

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

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多