简体   繁体   English

Jupyter Notebook 中的 Python fork 进程

[英]Python fork process inside Jupyter Notebook

I am running the following code inside a Jupyter notebook:我在 Jupyter 笔记本中运行以下代码:

import os

print("Start")
pid = os.fork()

if pid == 0:
    print("Child")
    os._exit(os.EX_OK)
else:
    print("Parent")
    
if pid != 0:
    # parent
    pid, status = os.waitpid(pid, 0)
    print("Done")

I am getting the following output "almost" every time:我每次都“几乎”得到以下输出:

Child孩子
Start开始
Parent家长
Done完毕

How is it that "Child" gets printed before "Start"?如何在“开始”之前打印“孩子”? Almost 9 out of 10 times, I get the output as above.几乎 10 次中有 9 次,我得到了如上的输出。 Occasionally, I find what is intuitively expected ("Start" being printed first, followed by "Parent" or "Child" and then finally ending with "Done").有时,我会发现直觉上的预期(首先打印“开始”,然后是“父”或“子”,最后以“完成”结束)。

When I run the same code directly on the console, I get the expected outcome each time:当我直接在控制台上运行相同的代码时,我每次都得到预期的结果:

Start开始
Parent家长
Child孩子
Done完毕

Why do we see this peculiar behavior within Jupyter notebooks?为什么我们会在 Jupyter 笔记本中看到这种特殊行为? And how to avoid this?以及如何避免这种情况?

It looks like stdout is block buffered, not line buffered.看起来 stdout 是块缓冲的,而不是行缓冲的。 The parent "Start\\n" is waiting in the output buffer.父级“Start\\n”正在输出缓冲区中等待。 The child "Child\\n" starts out in its own output buffer but is flushed on exit.子“Child\\n”在其自己的输出缓冲区中开始,但在退出时被刷新。 You could verify with import sys;print(sys.stdout.isatty()) .您可以使用import sys;print(sys.stdout.isatty()) The solution is to flush often解决办法是经常冲洗

print("Start", flush=True)

or if you have multiple things to print,或者如果你有很多东西要打印,

print("Foo")
print("Bar")
sys.stdout.flush()

At the moment there is no way to avoid this that I know.目前我知道没有办法避免这种情况。 Maybe there is a setting that is enabled.也许有启用的设置。 You could also try to add a wait.您也可以尝试添加等待。 Before you print child or parent, etc. Hopefully this helps a bit.在打印孩子或父母等之前。希望这会有所帮助。

Sleep like this:像这样睡觉:

import time
 
# Wait for 5 seconds
time.sleep(5)
 
# Wait for 300 milliseconds
# .3 can also be used
time.sleep(.300)

I would suggest waiting like .5 milliseconds to 1 second我建议等待 0.5 毫秒到 1 秒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM