首页 > 解决方案 > 如何使用在一个函数中声明的局部变量并将其实现到另一个函数?(没有全局变量或调用函数)

问题描述

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()

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

标签: python

解决方案


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

像这样设置主要:

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

然后更新_accept以接受 args:

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

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


推荐阅读