簡體   English   中英

程序使用線程()和子進程()運行一段時間

[英]programe run certain period of time using thread () and subprocess()

我想在我的 liunx os 上運行多個命令,所以我創建了一個腳本來運行多個命令,但是有些命令需要很長時間才能執行,但我想終止需要 1 分鍾以上才能執行的命令。 我怎樣才能做到這一點?

import subprocess
import threading
import time
from time import sleep

def prog(line):
    def worker(line):
        print(line)
        subprocess.call(line, shell=True )

    t = threading.Thread(target=worker, args=(line,))
    t.start()
    
f=open("a",'r')
for line in f:
    prog(line)

subprocess.call有一個timeout參數。
它在給定的超時(以秒為單位)后終止命令並引發TimeoutExpired

import subprocess
import threading

def prog(line):
    def worker(line):
        print(line)
        try:
            subprocess.call(line, shell=True, timeout=60)
        except subprocess.TimeoutExpired as e:
            print(e)

    t = threading.Thread(target=worker, args=(line,))
    t.start()
    
f=open("a",'r')
for line in f:
    prog(line)

這是一個可運行的最小示例: https://ideone.com/ZToaJU


另一個提示,雖然沒有被要求:您不需要將args=(line,)傳遞給工作人員 function。 由於它被聲明為嵌套的 function,它已經可以訪問progline變量:

import subprocess
import threading

def prog(line):
    def worker():
        print(line)
        try:
            subprocess.call(line, shell=True, timeout=60)
        except subprocess.TimeoutExpired as e:
            print(e)

    t = threading.Thread(target=worker)
    t.start()
    
f=open("a",'r')
for line in f:
    prog(line)

暫無
暫無

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

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