如何使用在一个函数中声明的局部变量并将其实现到另一个函数?(无全局变量或调用函数)

2024-04-26 21:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

import socket, sys

def create_socket(): # Creates a socket which connects two or more computers together
    host = ""
    port = 9999
    socket_ = socket.socket()
    try:
        host
        port
        socket_
        
    except socket.error as msg:
        print("Socket Creation Error: " + str(msg))

    return host, port, socket_


def bind_Socket(): # Binds the Socket and listening for connections

    host, port, socket_ = create_socket()
    try:
        host
        port
        socket_
        print("Binding the Socket: " + str(port))
        
        socket_.bind((host, port))
        socket_.listen(5)
        
    except socket.error as msg:
        print("Socket Creation Error: " + str(msg) + "Retrying....")
        bind_Socket()
    return host, port, socket_



def socket_accept(): # Establishes a connection with a client (socket must be listening)
    host, port, socket_ = bind_Socket()
    conn, address = socket_.accept()
    send_command(conn)
    print("Connection successful... " + "IP: " + address[0] + "\n" + "Port: " + address[1])

def send_command(conn): # Sends command to client
    host, port, socket_ = bind_Socket()
    cmd = ""
    while (cmd != "Quit"):
        cmd = input("Enter a command: ")
        if(len(str.encode(cmd)) > 0):
            conn.send(str.encode(cmd))
            client_response = str(conn.recv(1024,"UTF-8"))
            print(client_response, end="")
    else:
        conn.close()
        socket_.close()
        sys.exit()
    
        
def main():
    create_socket()
    bind_Socket()
    socket_accept()
main()

问题是,当我在main()中调用bind_Socket()时,它将打印两次“绑定套接字:9999”,因为它也在函数socket_accept()中被调用。我只想知道如何使用在一个函数中声明的相同变量,并在另一个函数中实现它,而不必像我那样使用全局变量或调用函数


1条回答
网友
1楼 · 发布于 2024-04-26 21:41:41

函数可以返回其他函数用作参数的对象

按如下方式设置主屏幕:

def main():
    _, _, socket_ = bind_Socket()
    socket_accept(socket_)

然后更新_accept以接受参数:

def socket_accept(socket_): 
    conn, address = socket_.accept()
    ....

从而将套接字对象传递给accept方法

相关问题 更多 >