运行python脚本时,守护进程线程在ipython中保持活动

时间:2018-09-11 12:24:51

标签: python multithreading ipython

请考虑以下代码行:

gate()

如果我将这些行复制并粘贴到ipython中,那么只要我愿意,我都可以键入import time import threading keepAlive = True def threadHandler(): print('thread started') while keepAlive: time.sleep(1) print('thread ended') tt = threading.Thread(name='SomeThread',target=threadHandler) tt.setDaemon(True) tt.start() 来使线程退出。哪个好!

但是,如果我将上面的代码保存到名为keepAlive = False的文件中,然后通过执行foo.py在ipython中运行,则在ipython shell中执行%run foo.py绝对没有效果,并且线程只是继续执行。就像keepAlive = False拥有自己的私有副本一样,线程启动时threadHandler()的值是什么。有办法解决吗?

1 个答案:

答案 0 :(得分:1)

1)您可以使用-i选项在笔记本的命名空间中运行脚本。参见this

%run -i "foo.py"

2)或获取代码,然后获取exec

# Get the code as a string
fin = open("foo.py", "r")
code = fin.read()

# Execute the code
exec(code)

# Doing this in a cell in notebook terminates the thread
keepAlive = False