Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python time.sleep()挂起_Python - Fatal编程技术网

Python time.sleep()挂起

Python time.sleep()挂起,python,Python,我正在尝试将一个python函数导入另一个python while循环。代码如下: test.py #!/usr/bin/python import time t = 15 print t def function_name_whatever_you_want(): t = 15 print t 睡眠测试 #!/usr/bin/python import time while True: import test time.sleep(10) import

我正在尝试将一个python函数导入另一个python while循环。代码如下:

test.py

#!/usr/bin/python
import time

t = 15
print t
def function_name_whatever_you_want():
    t = 15
    print t
睡眠测试

#!/usr/bin/python
import time

while True:
    import test
    time.sleep(10)
import test
while True:
    test.function_name_whatever_you_want()
    time.sleep(10)

当我运行sleep_test.py时,15被打印一次,然后循环挂起。我试图在10秒的延迟后连续打印15张。有没有人建议我如何使用我提供的代码来实现这一点?

问题不在于
睡眠。问题实际上出在
导入中

当Python导入模块时,它只导入一次。随后的
导入
将被忽略

您应该将模块重构为:


test.py

#!/usr/bin/python
import time

t = 15
print t
def function_name_whatever_you_want():
    t = 15
    print t

睡眠测试

#!/usr/bin/python
import time

while True:
    import test
    time.sleep(10)
import test
while True:
    test.function_name_whatever_you_want()
    time.sleep(10)

问题不在于
睡眠
。问题实际上出在
导入中

当Python导入模块时,它只导入一次。随后的
导入
将被忽略

您应该将模块重构为:


test.py

#!/usr/bin/python
import time

t = 15
print t
def function_name_whatever_you_want():
    t = 15
    print t

睡眠测试

#!/usr/bin/python
import time

while True:
    import test
    time.sleep(10)
import test
while True:
    test.function_name_whatever_you_want()
    time.sleep(10)

并不是说
time.sleep()
挂起的时间比预期的要长;这是因为尝试导入已经导入的模块不会重新导入它。如果确实要强制重新加载,请使用内置功能:

#!/usr/bin/python
import time

import test
while True:
    time.sleep(10)
    reload(test)
但是,您最好完全重新构造代码。这是一种相当丑陋的做事方式


(在Python3中,
reload
是到
imp
模块的。)

这不是
时间。sleep()
挂起(比预期的时间长);这是因为尝试导入已经导入的模块不会重新导入它。如果确实要强制重新加载,请使用内置功能:

#!/usr/bin/python
import time

import test
while True:
    time.sleep(10)
    reload(test)
但是,您最好完全重新构造代码。这是一种相当丑陋的做事方式


(在Python3中,
reload
是到
imp
模块的。)

我试过了,但15根本没有打印出来。代码无限期地运行,直到我中断它。我试过了,15个根本没有打印出来。代码无限期地运行,直到我打断它。@user3229243如果它帮助了你,你应该接受它作为你的答案。@user3229243如果它帮助了你,你应该接受它作为你的答案。这是非常丑陋的编码风格,为什么不将test.py中的内容转换成sleep_test.py中的单个函数并调用任意次数。这是一种非常丑陋的编码方式,为什么不将test.py中的内容转换成sleep_test.py中的单个函数并调用任意次数呢。