Python 如何使用在一个函数中声明的局部变量并将其实现到另一个函数?(无全局变量或调用函数)
问题是,当我在Python 如何使用在一个函数中声明的局部变量并将其实现到另一个函数?(无全局变量或调用函数),python,Python,问题是,当我在main()中调用bind\u Socket()时,它会打印两次“Binding The Socket:9999”,因为它也在函数Socket\u accept()中被调用。我只想知道如何使用在一个函数中声明的相同变量,并在另一个函数中实现它,而不必像我那样使用全局变量或调用函数。函数可以返回其他函数用作参数的对象 按如下方式设置主屏幕: import socket, sys def create_socket(): # Creates a socket which connec
main()
中调用bind\u Socket()
时,它会打印两次“Binding The Socket:9999”,因为它也在函数Socket\u accept()
中被调用。我只想知道如何使用在一个函数中声明的相同变量,并在另一个函数中实现它,而不必像我那样使用全局变量或调用函数。函数可以返回其他函数用作参数的对象
按如下方式设置主屏幕:
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()
然后更新\u accept
以接受参数:
def main():
_, _, socket_ = bind_Socket()
socket_accept(socket_)
从而将套接字对象传递给accept方法。不要调用bind_socket
两次socket\u accept
callsbind\u socket
callscreate\u socket
,因此您只需在main
中调用socket\u accept
,而无需调用其他任何函数…
def socket_accept(socket_):
conn, address = socket_.accept()
....