簡體   English   中英

在 python 循環中運行子進程

[英]run a subprocess in a python loop

在循環的每次迭代中,我在 python 中都有 for 循環,我想運行一個 bash 腳本,在它終止后繼續循環並再次運行 bash 腳本:

for batch in something:
    proc = Popen(['./mybash.sh'])
    proc.wait()

mybash.sh 腳本將計算一些東西並使用echo顯示一個值。 但是,當我運行此代碼時,它似乎只執行了一次 mybash.sh 腳本,因為我只能看到echo僅在第一次迭代時顯示的值。 代碼有什么問題? 順便說一句,我正在使用 python 3.5

it seems that it executes mybash.sh script only once的原因可能是:

  • 您的迭代只運行一次。
  • proc.wait()不返回。
  • ./mybash.sh無法正常工作。

你可以改變你的腳本是這樣的:

for batch in something:
    # to check the looping times
    print(batch)
    proc = Popen(['./mybash.sh'])
    # to check if the mybash.sh exit normally
    print(proc.wait())

Popen只是啟動一個進程。 你可能想要類似的東西

from subprocess import run, PIPE

for batch in something:
    print(run(['./mybash.sh'],
        stdout=PIPE, stderr=PIPE,
        check=True, universal_newlines=True).stdout)

check=True假定您的腳本返回有用且有效的退出代碼。

有關(更多!)更多信息,請參閱https://stackoverflow.com/a/51950538/874188

暫無
暫無

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

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