如果文件和打印机共享打开,我已经制作了一个可以在 LAN 中工作的小聊天程序。它基于简单的纯文本文件。有两种不同的脚本。一个处理发送部分,另一个处理接收部分。我试图将其作为一个脚本,但随后必须输入一条消息才能接收其他用户发送的消息。那么,我如何将它作为一个脚本呢?
发送脚本:
from sys import exit
LAN_NAME = "\\\\ONE-PC"
LAN_MSG_FILE = "%s\\Users\\Public\\me.txt" % LAN_NAME
TCHAT_VER = "1.1.0"
print "TChat - Version %s" % TCHAT_VER
print "Copyright(c) 2013 - Ahnaf Tahmid"
print "--------------------------------"
def send_data(src, msg):
_file_ = open(src, 'w')
_file_.truncate()
_file_.write(msg)
_file_.close()
msg = raw_input("[You]: ")
print "\n"
while True:
send_data(LAN_MSG_FILE, msg)
msg = raw_input("[You]: ")
print "\n"
if msg == "[exit]":
send_data(LAN_MSG_FILE, "[exit]")
raw_input("Press ENTER to exit.")
exit(0)
接收脚本:
from sys import exit
CLN = "\\\\TWO-PC"
CLN_MSG_FILE = "%s\\Users\\Public\\me.txt" % CLN
VER = "1.0.0"
def fetch_data(src):
_file_ = open(src, 'r')
message = _file_.read()
_file_.close()
return message
msg = " "
msg_to_display = "x"
print "TChat Receiver v%s." % VER
print "Copyright(c) 2013 - Ahnaf Tahmid."
print "---------------------------------"
print "\n"
while True:
msg = fetch_data(CLN_MSG_FILE)
if msg_to_display == msg:
pass
else:
msg_to_display = msg
if msg_to_display == "[exit]":
print "[%s] has disconnected.";
raw_input("Press ENTER to exit")
exit(0)
print "[%s]: %s\n" % (CLN, msg_to_display)
注意:这两个脚本必须在两台 PC 上运行。一个接收消息并显示它们,另一个发送它们。
这是我尝试将它们组合在一起的尝试:
from sys import exit
LAN_NAME = "\\\\ONE-PC"
LAN_MSG_FILE = "%s\\Users\\Public\\me.txt" % LAN_NAME
CLN = "\\\\TWO-PC"
CLN_MSG_FILE = "%s\\Users\\Public\\me.txt" % CLN
TCHAT_VER = "1.0.2"
def fetch_data(src):
file_ = open(src, 'r')
file_data = file_.read()
file_.close()
return file_data
def send_data(src, data):
file_ = open(src, 'w')
file_.truncate()
file_.write(data)
file_.close()
def clean_cache(src):
file_ = open(src, 'w')
file_.truncate()
file_.close()
print "TChat - Version %s" % TCHAT_VER
print "Copyright(c) 2013 - Ahnaf Tahmid"
print "--------------------------------"
print "\n"
print "To exit anytime, type in [exit]"
print "\n"
msg = raw_input("[You]: ")
msg_lan = " "
while msg != "[exit]":
send_data(LAN_MSG_FILE, msg)
print "\n"
print "Fetching data.."
msg_lan = fetch_data(CLN_MSG_FILE)
while len(msg_lan) <= 1:
msg_lan = fetch_data(CLN_MSG_FILE)
clean_cache(CLN_MSG_FILE)
print "\n"
print "[Friend]: %s" % msg_lan
print "\n"
msg = raw_input("[You]: ")
print "\n"
print "Thanks for using TChat."
raw_input("Press ENTER to exit")
exit(0)
任何帮助表示赞赏。