使用Python在类或函数外部返回一个字符串

时间:2016-07-28 06:01:36

标签: python

我是OOP的新手,我正在试图弄清楚如何获得课外某些内容的结果,以便决定在我的课程中下一步该做什么。

我解压缩文件,如果花费的时间太长,我希望该进程终止。这段代码就是这样做的:

class Command(object):
    def __init__(self,cmd):
        self.cmd = cmd
        self.process = None

    def run(self,timeout):
        def target():
            print("Thread started")
            self.process = subprocess.Popen(self.cmd)
            self.process.communicate()
            print("Thread finished")

        thread = threading.Thread(target=target)
        thread.start()

        thread.join(timeout)
        if thread.is_alive():
            print("\nTerminating process")
            self.process.terminate()
            thread.join()            
        print(self.process.returncode)

def unzip_file(file,dirout,attempt):
    just_name = os.path.splitext(file)[0]    
    print('unzip started at {} for {}'.format(datetime.datetime.now(),file))
    command = Command(zip_exe+' x '+file+' -o'+path+dirout)
    command.run(timeout = 300)  

...但是,如果我想获取命令输出,在类内部调用的函数之外呢?对称为' tmp'的变量说。我添加了两行带注释的行来说明我尝试做的事情当然会返回错误。

class Command(object):
    def __init__(self,cmd):
        self.cmd = cmd
        self.process = None

    def run(self,timeout):
        def target():
            print("Thread started")
            self.process = subprocess.Popen(self.cmd)
            self.tmp = self.proc.stdout.read() #get the command line output
            self.process.communicate()
            print("Thread finished")

        thread = threading.Thread(target=target)
        thread.start()

        thread.join(timeout)
        if thread.is_alive():
            print("\nTerminating process")
            self.process.terminate()
            thread.join()            
        print(self.process.returncode)

def unzip_file(file,dirout,attempt):
    just_name = os.path.splitext(file)[0]    
    print('unzip started at {} for {}'.format(datetime.datetime.now(),file))
    command = Command(zip_exe+' x '+file+' -o'+path+dirout)
    command.run(timeout = 300)
    print(self.tmp)    #print the command line output (doesn't work)

2 个答案:

答案 0 :(得分:1)

此行self.tmp = self.proc.stdout.read()将一些数据放入成员变量中。然后,您可以通过简单地使用对象的引用来在类之外使用它:

...
command.run(timeout = 300)
print(command.tmp)  

答案 1 :(得分:1)

您的问题似乎是函数self中未定义标识符unzip_file。尝试替换

print(self.tmp)    #print the command line output (doesn't work)

print(command.tmp) 

标识符self在类的范围内使用时具有特殊含义,并且引用该类的实例。在其他地方使用时(如在unzip_file中),标识符没有特殊含义,只是一个常规的未定义标识符。

除了您的实际问题,您可能想要研究线程之间的通信机制。如果您已经了解基础知识,Queue module是一个值得关注的好地方。如果您不熟悉该主题,那么this one是一个不错的介绍。