[英]Async Python function call upon a Bash execution (through Python Popen)
我正在Python腳本內執行bash命令(下載文件)。
def execBashCmd(bash_cmd):
process = Popen([bash_cmd], stdout=PIPE, stderr=PIPE, shell=True)
bash命令在stdout中輸出進度(刷新),如下所示:
Downloading File - 20.66 MiB/165.31 MiB
我希望能夠以固定的間隔調用python函數以在我的python代碼中的某處更新進度(我會用正則表達式或類似的東西捕獲)。
cmd = "gsutil cp -n ...." # A Bash command downloading a file and displaying a status in stdout while busy.
code = utils.execBashCmd(cmd)
self.setProgress(BASH_CURRENT_PROGRESS) # This line should be asynchrone and called upon the bash command lifetime
有沒有辦法做到這一點?
我希望能夠以固定的間隔調用python函數以在我的python代碼中的某處更新進度(我會用正則表達式或類似的東西捕獲)。
只要字節數足夠大,您就可以隨時調用os.read(process.stdout.fileno(), 4096)
並獲取bash命令的輸出進度(可能是多次更新)。 如果您不希望此調用在下一個進度輸出之前一直阻塞,則可以使管道變為非阻塞狀態
fcntl.fcntl(process.stdout, fcntl.F_SETFL, os.O_NONBLOCK)
並做例如
try:
progress = os.read(process.stdout.fileno(), 4096)
except OSError:
# no progress data
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.