簡體   English   中英

如何使用python中的命令模塊在后台運行命令?

[英]How do I run a command in background using commands module in python?

我想使用 python 2.7 在后台運行系統命令,這就是我所擁有的:

import commands
path = '/fioverify.fio'

cmd= "/usr/local/bin/fio" + path + " "+ " &"
print cmd
handle = commands.getstatusoutput(cmd)

這失敗了。 如果我刪除&符號&它的工作原理。 我需要在后台運行一個命令( /usr/local/bin/fio/fioverifypath )。

有關如何完成此操作的任何指示?

不要使用commands 它已被棄用,實際上對您的目的沒有用。 改用subprocess

fio = subprocess.Popen(["/usr/local/bin/fio", path])

與您的進程並行運行fio命令,並將變量fio綁定到進程的句柄。 然后您可以調用fio.wait()等待進程完成並檢索其返回狀態。

使用子進程模塊, subprocess.Popen允許您將命令作為子進程(在后台)運行並檢查其狀態。

您也可以嘗試sh.py ,它支持后台命令:

import sh

bin = sh.Command("/usr/local/bin/fio/fioverify.fio")
handle = bin(_bg=True)
# ... do other code ...
handle.wait()

使用 Python 2.7 在后台運行進程

commands.getstatusoutput(...)是不夠聰明處理后台進程,使用subprocess.Popenos.system

重現commands.getstatusoutput如何在后台進程中失敗的錯誤:

import commands
import subprocess

#This sleeps for 2 seconds, then stops, 
#commands.getstatus output handles sleep 2 in foreground okay
print(commands.getstatusoutput("sleep 2"))

#This sleeps for 2 seconds in background, this fails with error:
#sh: -c: line 0: syntax error near unexpected token `;'
print(commands.getstatusoutput("sleep 2 &"))

subprocess.Popen 如何在后台進程上成功的演示:

#subprocess handles the sleep 2 in foreground okay:
proc = subprocess.Popen(["sleep", "2"], stdout=subprocess.PIPE)
output = proc.communicate()[0]
print(output)

#alternate way subprocess handles the sleep 2 in foreground perfectly fine:
proc = subprocess.Popen(['/bin/sh', '-c', 'sleep 2'], stdout=subprocess.PIPE)
output = proc.communicate()[0]
print("we hung for 2 seconds in foreground, now we are done")
print(output)


#And subprocess handles the sleep 2 in background as well:
proc = subprocess.Popen(['/bin/sh', '-c', 'sleep 2'], stdout=subprocess.PIPE)
print("Broke out of the sleep 2, sleep 2 is in background now")
print("twiddling our thumbs while we wait.\n")
proc.wait()
print("Okay now sleep is done, resume shenanigans")
output = proc.communicate()[0]
print(output)

os.system 如何處理后台進程的演示:

import os
#sleep 2 in the foreground with os.system works as expected
os.system("sleep 2")

import os
#sleep 2 in the background with os.system works as expected
os.system("sleep 2 &")
print("breaks out immediately, sleep 2 continuing on in background")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM