在Debian系统上登录时运行一个简单的Python TCP服务器
问题描述:
我想在启动时运行一个简单的服务器。我使用的操作系统是Debian 6.0。我在.profile中添加了一行以运行python脚本:python /root/desktopnavserver2.py
计算机启动并登录,但出现下面的错误。当我在debian.profile中没有添加行时,脚本运行良好,我只是在控制台中自己运行脚本。任何帮助?在Debian系统上登录时运行一个简单的Python TCP服务器
错误跟踪:
Traceback (most recent call last):
File "/root/Desktop/navserver2.py", line 39, in <module>
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
File "/usr/lib/python2.6/SocketServer.py", line 402, in __init__
self.server_bind()
File "/usr/lib/python2.6/SocketServer.py", line 413, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
error: [Errno 98] Address already in use
来源:
#!/usr/bin/python
import SocketServer
import serial
com2 = serial.Serial(
port = 1,
parity = serial.PARITY_NONE,
bytesize = serial.EIGHTBITS,
stopbits = serial.STOPBITS_ONE,
timeout=3,
xonxoff = 0,
rtscts = 0,
baudrate = 9600
)
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
#print "%s wrote:"%self.client_address[0]
#print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
com2.write(self.data)
if __name__ == "__main__":
HOST, PORT = "192.168.0.200", 14052 #change to 192.168.0.200
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
答
我相信.profile
由每个将自身标识为登录shell的shell实例执行。可能你有多个这样的外壳。
无论如何,在您的.profile
中放置单实例脚本是一个坏主意 - 这意味着您只能有一个登录会话,下一个会话会导致此错误。
答
线error: [Errno 98] Address already in use
解释了它 - 找出什么在该端口在进入运行程序(提示:是.py被称为两次?)
hmms有时脚本运行正常,而其他脚本运行不正常。听起来像脚本实际上是运行两次,如你所建议的,但我不知道为什么。当我得到这个错误并输入lsof -i时,我可以看到有一个使用相同端口的python脚本。问题是,如果我从启动脚本的.profile中删除该行,则没有脚本运行的实例。 – Richard 2012-03-14 14:28:13
您是否运行多个终端/窗口?如果是这样,当您通过.profile中的'ps -ef'行运行时,您必须检查脚本是否已经运行 – KevinDTimm 2012-03-14 14:57:23