相关疑难解决方法(0)

使用模块'subprocess'和超时

这是运行任意命令返回其stdout数据的Python代码,或者在非零退出代码上引发异常:

proc = subprocess.Popen(
    cmd,
    stderr=subprocess.STDOUT,  # Merge stdout and stderr
    stdout=subprocess.PIPE,
    shell=True)
Run Code Online (Sandbox Code Playgroud)

communicate 用于等待进程退出:

stdoutdata, stderrdata = proc.communicate()
Run Code Online (Sandbox Code Playgroud)

subprocess模块不支持超时 - 能够终止运行超过X秒的进程 - 因此,communicate可能需要永久运行.

在旨在在Windows和Linux上运行的Python程序中实现超时的最简单方法是什么?

python multithreading subprocess timeout

303
推荐指数
15
解决办法
26万
查看次数

在Python的调用者线程中捕获线程的异常

我对Python和多线程编程很新.基本上,我有一个脚本,将文件复制到另一个位置.我希望将它放在另一个线程中,以便我可以输出....以指示脚本仍在运行.

我遇到的问题是,如果文件无法复制,它将引发异常.如果在主线程中运行,这是可以的; 但是,具有以下代码不起作用:

try:
    threadClass = TheThread(param1, param2, etc.)
    threadClass.start()   ##### **Exception takes place here**
except:
    print "Caught an exception"
Run Code Online (Sandbox Code Playgroud)

在线程类本身,我试图重新抛出异常,但它不起作用.我看到这里的人问类似的问题,但他们似乎都在做一些比我想做的更具体的事情(而且我不太了解提供的解决方案).我见过人们提到使用它sys.exc_info(),但我不知道在哪里或如何使用它.

非常感谢所有帮助!

编辑:线程类的代码如下:

class TheThread(threading.Thread):
    def __init__(self, sourceFolder, destFolder):
        threading.Thread.__init__(self)
        self.sourceFolder = sourceFolder
        self.destFolder = destFolder

    def run(self):
        try:
           shul.copytree(self.sourceFolder, self.destFolder)
        except:
           raise
Run Code Online (Sandbox Code Playgroud)

python multithreading exception-handling exception

178
推荐指数
10
解决办法
15万
查看次数

Python,Popen和select - 等待进程终止或超时

我使用以下命令运行子进程:

  p = subprocess.Popen("subprocess", 
                       stdout=subprocess.PIPE, 
                       stderr=subprocess.PIPE, 
                       stdin=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

此子进程可以立即退出stderr上的错误,也可以继续运行.我想检测这些条件中的任何一个 - 后者等待几秒钟.

我试过这个:

  SECONDS_TO_WAIT = 10
  select.select([], 
                [p.stdout, p.stderr], 
                [p.stdout, p.stderr],
                SECONDS_TO_WAIT)
Run Code Online (Sandbox Code Playgroud)

但它只是返回:

  ([],[],[])
Run Code Online (Sandbox Code Playgroud)

无论哪种条件.我能做什么?

python select subprocess timeout popen

22
推荐指数
2
解决办法
4万
查看次数