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()
问题是当我调用bind_Socket()
in时,main()
它会打印两次“Binding the Socket: 9999”,因为它也在函数中被调用socket_accept()
。我只想知道如何使用在一个函数中声明的相同变量并在另一个函数中实现它,而不使用全局变量或像我一样调用函数。
解决方案
函数可以返回对象以供其他函数用作参数。
像这样设置主要:
def main():
_, _, socket_ = bind_Socket()
socket_accept(socket_)
然后更新_accept
以接受 args:
def socket_accept(socket_):
conn, address = socket_.accept()
....
从而将套接字对象传递给accept 方法。
推荐阅读
- json - Angular - 如何优化 JSON.stringify?
- python - 用对象的属性替换 Pandas 系列中的对象
- django - 在 Django 模板中嵌入 PDF 媒体文件
- delphi - 如何将 OnHelp 事件处理程序附加到 Application 对象?
- excel - 在熊猫中编辑单个excel表
- python - 我可以存储一个 Parquet 文件,其字典列的值中包含混合类型吗?
- javascript - 使用 D3 在 SVG 中制作条形图后,它不适合整个 SVG
- ruby-on-rails - 向现有数据集添加键和关联
- coq - 自然数列表中的最大值
- javascript - 在表中添加多行并在同一行中添加嵌套行