为什么我的python脚本不能继续听

时间:2014-10-27 00:29:59

标签: python multithreading multiprocessing

Hello stackoverflow用户,所以我有这个问题,我试图编写一个Web服务器,但脚本结束后,我甚至可以测试它是否工作。所以我的问题是如何制作脚本以使其永久运行?

#import threading
#import socket
#import signal  # Signal support (server shutdown on signal receive)
import multiprocessing
#import queue

def MasterProcessA():
    import socket
    import multiprocessing
    import threading
    HOST = '97.107.139.231'   # Symbolic name, meaning all available interfaces
    PORT = 8080 # Arbitrary non-privileged port
    #print(PORT)
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #print 'Socket created'

    #Bind socket to local host and port
    #try:
    socket.bind((HOST, PORT))
    #except socket.error as msg:
    ##print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    #print 'Socket bind complete'

    #Start listening on socket
    socket.listen(100)
    print "starting server"
    def ConnProcessA():
        print "thread step one"
        Conn, Address = socket.accept()
        t = threading.Thread(target=ConnectionProcessorA)
        print "thread step two"
        #t.daemon = True
        t.start()
        #print("A Got connection from:", Address)
        DataRecived = Conn.recv(1024) #receive data from client
        DataRecived = bytes.decode(DataRecived) #decode it to string
        print DataRecived
        Conn.send("HELLO World")
        Conn.clouse()

    ConnProcessA = threading.Thread(target=ConnProcessA)
    #t.daemon = True
    ConnProcessA.start()

MasterProcessA = multiprocessing.Process(target=MasterProcessA)
MasterProcessA.start()

1 个答案:

答案 0 :(得分:1)

您的代码存在多个问题。

  • 线程没有运行。你需要修改: ConnProcessA.start() ConnProcessA.join()
  • ConnectionProcessorA未包含在您粘贴的代码中。所以我要评论这两行: t = threading.Thread(target=ConnectionProcessorA) t.start()
  • 名称阴影。请参考以下这些行: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ConnProcessA = threading.Thread(target=ConnProcessA) MasterProcessA = multiprocessing.Process(target=MasterProcessA)
  • 您使用现有模块/函数名称命名实例。名称阴影非常危险。只要尝试两次执行任意三行,您就会看到错误。
  • 另一方面,如果直截了当,可以重复使用变量来保存不同的东西。例如,以下两行足够接近以避免混淆: DataRecived = Conn.recv(1024) #receive data from client DataRecived = bytes.decode(DataRecived) #decode it to string
  • 看起来您的套接字服务器要持续监听同一个端口,那么您可能需要添加s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)。正如the doc的最底部所说的那样。
  • 不太严重的一点,在Python编码惯例中,CapWords通常用于类名ref。您将它用于函数名和变量名。最好保持代码一致。