作为一个小项目,我创建了一个小型聊天室。接下来是代码,我可以指出我是编程新手,因此结构可能效率不高:
import re, time
user_name = 0
password = 0
chatroom = 0
from users import users
def startup():
global user_name, password, chatroom
print "\n" * 100
user_name = raw_input("Your username: ").upper()
if users.has_key(str(user_name).lower()) == True:
password = str(raw_input("Password: "))
while str(users[user_name.lower()]) != str(password):
print "Incorrect password."
time.sleep(2)
startup()
else:
chatroom = raw_input("Room name: ").lower()
chat()
else:
print "Invalid username."
time.sleep(2)
startup()
def showchat():
global user_name
file = open(str(chatroom) + ".txt","r+")
messages = str(file.read()[-700:])
file.close
messages = messages.rstrip('\n')
print "\n" * 40
print messages
print "------ type 'r' to refresh the screen ------"
def writechat():
global user_name, chatroom
n = raw_input("________________________________________________________" + "\n" + user_name + ": ")
if user_name.lower() == 'admin':
if n == "clear":
file = open(str(chatroom) + ".txt","w")
file.write("")
file.close
elif n == "addnewuser":
x = "'" + raw_input("new username: ") + "'"
y = "'" + raw_input("new password: ") + "'"
file = open("users.py","r").read()
file = file.replace("'username' : 'password',", x + " : " + y + "," + "'username' : 'password',")
open("users.py","w").write(file)
elif n == "r":
chat()
elif n == "logout":
startup()
else:
file = open(str(chatroom) + ".txt","a")
file.write(user_name + ": " + str(n) + "\n")
file.close()
else:
if n == "r":
chat()
elif n == "changepassword":
file = open("users.py","r")
file.read()
oldpass = raw_input("New password: ")
users[user_name.lower()] = oldpass
print users
file.close()
file = open("users.py","w")
file.write("users = " + str(users)) #here
file.close()
elif n == "logout":
startup()
else:
file = open(str(chatroom) + ".txt","a")
file.write(user_name + ": " + str(n) + "\n")
file.close()
def chat():
showchat()
writechat()
chat()
startup()
只要存在chatroom.txt文件以及users.py,此代码在python中完全正常。 一旦我将它转换为.exe,问题就出现了,除了users.py文件没有永久写入(它暂时写入)时,它应该正常工作,相关的编码被标记为#here。
我的设置代码如下:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe' : {
'packages': ['users'],
"bundle_files" : 2,
}},
console = [{'script': "chatroom.py"}],
zipfile = None,
)
users.py只是(user:password)的字典:
users = {
'admin' : '2588619',
'john' : '1234',
'username' : 'password',
}
那么如何将其转换为.exe并使其永久写入users.py?
答案 0 :(得分:1)
py2exe创建的包只是一个自动解压缩的归档文件,其中包含python解释器和您的程序。每次运行.exe时,内部的所有内容都会被提取到一个临时目录中,程序由提取的解释器运行。
这意味着,如果将users.py
与源代码放在一起,那么您想要实现的目标就无法实现。
您应该在某个用户目录中创建users.py
文件,例如:
users = open(os.path.join(os.path.expanduser('~'), '_MyProgram', 'users.py'))
显然你也应该确保这个目录存在,并最终创建它。
这可以通过py2exe传递data_files
参数自动完成。
答案 1 :(得分:0)
我认为这是以users.py的名义py2exe认为它是一个需要处理的文件。将其重命名为users.db或其他内容。看看是否有效。