0

我的代码似乎挂在这个 popen 调用上

command = "ls"
commandList = shlex.split(command)
print("Executing " + command +"\n")
print(commandList)
output = "#" * 10 + "\n" + server.name + "\n\n"
process = subprocess.Popen(
    command,
    shell=True,
    stdin=subprocess.PIPE, 
    stdout=subprocess.PIPE)
output = process.communicate()[0]
#scriptRunner.threadComplete(output)
return output

代码在executeScriptOverSSH方法上SshWorker

class WorkerThread(threading.Thread):
    def __init__(self, pathToScript, server, runner):
        super(WorkerThread, self).__init__()
        self.scriptRunner = runner
        self.server = server
        self.pathToScript = pathToScript
        self.sshWorker = SshWorker.SshWorker()

    def run(self):
        print('Thread Starting')
        output = self.sshWorker.executeScriptOverSSH(
            self.server, 
            self.pathToScript)
        print('Thread Finishing!')
        self.scriptRunner.threadComplete(output)`

线程永远不会通过调用Popen- 我已经通过使用 print 语句进行了检查。有任何想法吗?

4

1 回答 1

0

我已经运行了下面的代码,它运行正常。您提到“如果返回码不为零,则 check_output barfs”,请查看check_output 文档,它会引发CalledProcessError异常,您可以捕获该异常并在一个不错的结构中包含所有错误详细信息。

import threading, subprocess, random, time, pprint
from subprocess import check_output

class WorkerThread(threading.Thread):
    def __init__(self, user, host, script, runner):
        super(WorkerThread, self).__init__()
        self.user = user
        self.host = host
        self.script = script
        self.runner = runner

    def run(self):
        cmd = "ssh {user}@{host} 'bash -s' < {script}".format(**self.__dict__)
        self.runner.complete(check_output(cmd, shell=True))

class Runner(object):
    def complete(self, output):
        print 'output:\n', output

WorkerThread('marwan', 'homebox', 'local_script.sh', Runner()).start()

上面的代码遵循您在问题中发布的相同结构。但我不建议您采用这种方法,这里有一些建议:

  • 从您称为 runner 的 WorkerThread 中,我不知道 runner 的详细信息,但是在进行多线程编程时,最强大的线程安全选项是使用Queue进行通信。
  • 有许多优秀的图书馆可以做你正在做的事情。他们经过充分测试并且干净利落。paramiko很棒,Fabric也很棒。

简单的结构远程运行示例

from fabric.api import run

def anonymous():
    run("uname -a")
于 2012-10-02T20:55:48.540 回答