我有两个python文件,并使用以下命令将一个文件导入另一个文件:
in test1.py
import test2
test2.py
import os
from socket import *
host = "192.168.1.253" # set to IP address of target computer
port = 8081
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
data = "102"
UDPSock.sendto(data, addr)
UDPSock.close()
有什么方法可以导入具有延迟时间(以秒为单位)的test2.py吗?
谢谢
答案 0 :(得分:1)
import time
time.sleep(9) #delay for 9 seconds
import test2
希望这会有所帮助:)
答案 1 :(得分:0)
虽然可以通过将较慢的内容放到文件中来延迟import
来延迟import
,但这可能不是解决实际问题的好方法,因为您想要导入触发的行为被延迟。
一种更好的方法是将该行为放入函数中,然后在导入后随时可以调用该函数。导入不再直接触发该行为,因此您可以将print("doing stuff")
语句保留在大多数人期望的文件顶部。
这是一些更简化的示例。
基于您当前代码的版本:
library.py
import library # oops, this triggers the print too soon
script.py
import time
time.sleep(10) # this does the delaying
import library # this triggers the print, but it's unexpected to see an import here
一个替代脚本,在导入库之前会有延迟(虽然不是一个好主意,但这是您特别要求的):
script.py:
def stuff():
print("doing stuff")
更好的解决方案是将库的行为移至函数中,因此导入的时间不再重要(仅调用函数的时间):
library.py:
import time
import library # we can do the import whenever we want, doesn't cause any printing
time.sleep(10)
library.stuff() # do the stuff here
script.py:
library
如果您希望if __name__ == "__main__":
stuff()
模块也可用作脚本,则可以将此代码添加到文件的底部,以便它有时会调用函数本身:
if __name__ == "__main__":
__main__
行是一个样板代码,它检查当前模块是否是程序的itertools.dropwhile
模块(如果它是作为脚本运行的,则为true)。相反,如果要导入模块,则该条件将为false,因此该函数将不会运行(直到真正的脚本决定调用它)。