我正在为一个没有 得到正确的更新。
我要做的是实例化一个类对象并调用其方法之一。此方法将启动一个处理异步结果的流程。该过程具有一个回调方法,该方法是我的对象的一个实例方法。 当我的过程完成时,应该通过回调方法来更新类变量。这没有发生。在回调执行期间,一切看起来都很好。
有人可以指出我在这里做错了什么吗?
这是我的代码:
import subprocess
import logging
try:
from multiprocessing import Process
except ImportError:
# For pre 2.6 releases
from threading import Thread as Process
def runner(printout, callback):
command = "ls"
data = subprocess.Popen(
command,
bufsize=100000,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# wait until finished
# get output
(last_output, myerr) = data.communicate()
last_output = bytes.decode(last_output)
myerr = bytes.decode(myerr)
if len(myerr) > 0:
logging.debug(myerr)
if printout and callable(callback):
callback(last_output)
return
class MyClass(object):
def __init__(self, myres):
if myres is None:
logging.warning("No result object given. Results will be printed to stdout only!")
self.results = myres
def _result_callback(self, scan_results):
if scan_results:
for line in scan_results.splitlines():
self.results = self.results + line
print(self.results)
def task_starter(self):
process = Process(
target=runner,
args=(True, self._result_callback),
)
process.daemon = True
process.start()
while process.is_alive():
logging.debug("Still running...")
process.join(2)
result = ""
myjob = MyClass(result)
myjob.task_starter()
print("\n")
print("SAME RESULT: %s" % myjob.results)
预先感谢, 巧克力卷