简体   繁体   English

程序使用线程()和子进程()运行一段时间

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

I want to run multiple commands on my liunx os so I create a script to run multiple commands but some command take too much time to execute but I want terminate the commands which take more then 1 min to execute.我想在我的 liunx os 上运行多个命令,所以我创建了一个脚本来运行多个命令,但是有些命令需要很长时间才能执行,但我想终止需要 1 分钟以上才能执行的命令。 How can i do that?我怎样才能做到这一点?

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 has a timeout parameter. subprocess.call有一个timeout参数。
It kills the command after a given timout (in seconds) and raises TimeoutExpired .它在给定的超时(以秒为单位)后终止命令并引发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)

Here a runnable minimal example: https://ideone.com/ZToaJU这是一个可运行的最小示例: https://ideone.com/ZToaJU


Another hint, while not asked for: you don't need to pass args=(line,) to the worker function.另一个提示,虽然没有被要求:您不需要将args=(line,)传递给工作人员 function。 As it is declared as a nested function, it already has access to the line variable of prog :由于它被声明为嵌套的 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