【问题标题】:Process ends before expected Python进程在预期 Python 之前结束
【发布时间】:2017-12-11 22:01:09
【问题描述】:

我正在 Pycharm 中编写一个简单的 Python 程序,将 csv 数据库导入到 Mongodb,在导入时显示进度条,在导入所有文档后,运行其他一些功能...

由于我使用子进程指令来运行 mongoimport 命令,我必须做一些等待其他函数在 mongimport 之前不执行的操作。

问题来了:如果我使用 subprocess.wait() 进度条会停止更新,直到 mongoimport 结束,否则如果我使用 sleep() 也会发生同样的情况......

所以我尝试在同一进程中运行 mongoimport 子进程和更新进度条的函数。然后我使用“空”循环检查是否 process.is_alive() 所以主程序什么都不做,而进程正在导入和更新进度条......但它在预期之前退出了循环!早在 mongoimport 之前,进度条功能都没有结束。

代码如下:

def mainFunction(self):
    process1 = Process(target=self.execc())
    process1.start()

    while process1.is_alive():
        print("IM IN PROCESS 1")

    # THIS IS PRINTED BEFORE "execc()" ENDS
    print("IM OUT!")

    # other functions
    self.toISO()
    self.createFrec()
    self.sort()


def execc(self):

    p = subprocess.Popen(['mongoimport', '-d', 'tfg', '-c', 'myCol', '--type', 'csv', '--file', './myFile.csv', '--headerline'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


    # shows and updates the progress bar while mongoimpor
    self.showProgress()


# RECURSIVE FUNCTION
# updates the progress bar every 200ms
def showProgress(self):
    bytes = self.db.command('collStats', self.coll_name.get())
    self.pBar['value'] = bytes['size']

    if bytes['size'] < self.maxbytes:
        self.pBar.after(200, self.showProgress)

【问题讨论】:

  • 顺便说一句,process1 = Process(target=self.execc()) 是假的。应该是process1 = Process(target=self.execc)。你的代码只是执行,所以没有子进程 ro tun
  • omg...我现在感觉很糟糕...我更改了它,但它发生了同样的情况:虽然 mongoimport 仍在运行,但 showProgress() 不起作用并且 while 循环中断...
  • 你上面提到的wait-call 在哪里?在execc 中创建子进程,然后您不必等待它退出。
  • 我删除了等待,因为我希望 subprocess 和 showProgress() 函数同时运行。我只想等待#other函数

标签: python mongodb process


【解决方案1】:

我认为您不需要多处理方法来处理这种情况。 相反,您可以简单地使用Popen.poll 来检查子进程是否已终止。我认为这样的事情应该可行

p = subprocess.Popen(['mongoimport', '-d', 'tfg', '-c', 'myCol', '--type', 'csv', '--file', './myFile.csv', '--headerline'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while p.poll() is None:

    # shows and updates the progress bar while mongoimpor
    self.showProgress()

if p.returncode != 0:
    raise Exception("mongoimport terminated with exit code {}".format(p.returncode))

【讨论】:

  • 感谢您的帮助....但是,请注意 showProgress() 是一个递归函数,此外,如果我将该函数放在一个 while 循环中,它将被多次执行 maaaaaany :/
  • 只需添加一个sleep(0.2) 并删除递归
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
相关资源
最近更新 更多