我最近完成了一个项目,现在我希望将该程序分成多个文件以提高可读性和将来的改进,但是我不知道该怎么做。我已将与某个主题相关的所有功能拆分为它们自己的文件(数据库文件中的数据库文件,哈希文件为哈希等)
编辑:我相信正确的术语是“模块”(我正尝试将程序拆分为“文件”,因此对缺乏正确的术语感到抱歉)
为此,我完成了“从foo导入*”,这是一种不好的做法,但是在我的编辑器pycharm中,它不显示任何立即错误,与执行“ import foo”不同。
但是,当我运行程序时,出现错误,提示我导入的文件正在使用未定义的变量(在主程序中定义) 这是代码段:
from Data_Funcs import *
if __name__ == "__main__":
DBSetup()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
while True:
conn, addr = s.accept()
connThread = Thread(target=handler, args=(conn, addr))
connThread.daemon = True
connThread.start()
这是Data_Funcs:
def receiveData(FROM=""):
print("In receive data")
if FROM:
print("From:", FROM)
# sendPickledData(dataReady)
dataString = conn.recv(4096)
try:
dataString = pickle.loads(dataString)
except pickle.UnpicklingError as err:
print("Pickling error:")
print(err)
time.sleep(0.2)
print("Data received:")
print(dataString)
return dataString
def sendPickledData(data):
print("In sendPickled,\nSending:",data)
data = pickle.dumps(data)
conn.sendall(data)
time.sleep(0.2)
但是,当我运行程序时,出现错误:
File "C:\Users\Green\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\Green\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/Green/Desktop/Py Proj/Project_Server_Handler_v5.py", line 200, in handler
data = receiveData("handler")
File "C:\Users\Green\Desktop\Py Proj\Data_Funcs.py", line 7, in receiveData
dataString = conn.recv(4096)
NameError: name 'conn' is not defined
尽管在主程序的“如果 name ==' main ':”部分中定义了变量conn