Python导入其他脚本时如何避免执行该脚本并使用其变量?
Hey there! Let's work through your three main issues step by step: stopping the server script from running when imported, enabling bidirectional message transfer, and making decoded messages show up cleanly in the command prompt.
1. Stop Server Script from Running on Import
The problem here is that all top-level code in a Python script runs when you import it. Right now, your entire server setup and loop are at the top of Connection.py, so importing it in Client.py triggers the server to start up again, causing conflicts.
The fix is simple: wrap your server's execution code in an if __name__ == "__main__": block. This ensures the server logic only runs when you directly execute Connection.py, not when it's imported as a module.
2. Implement Bidirectional Messaging
Right now, your server sends one message then closes the connection, and the client only receives one message. To enable back-and-forth communication, we'll modify both scripts to keep the connection open and loop through send/receive actions until a termination command (like "exit") is entered.
3. Clean Up Message Decoding
Your current client code has an error where you try to decode a variable usermessage that hasn't been defined yet. We'll fix that by properly receiving the message, decoding it from base64, and converting it to a readable string before printing.
Modified Server Script (Connection.py)
import socket import base64 def start_server(): neverland = True # Create socket object s = socket.socket() print("Socket created") # Choose port number for connection port = 29759 # Bind to the port (use '0.0.0.0' to accept connections from any address) s.bind(('0.0.0.0', port)) print(f"Currently using port #{port}") # Make socket listen for connections s.listen(5) print("Currently waiting on a connection...") # Loop for establishing a connection and sending/receiving messages while neverland: # Establish a connection c, addr = s.accept() print(f"Got a connection from {addr}") # Keep the connection open for bidirectional messaging while True: # Send message to client server_msg = input("Enter your message (type 'exit' to close): ") if server_msg.lower() == "exit": # Encode and send exit signal encoded_msg = base64.b64encode(server_msg.encode("utf-8")) c.send(encoded_msg) print("Closing connection...") c.close() break # Encode and send message encoded_msg = base64.b64encode(server_msg.encode("utf-8")) c.send(encoded_msg) # Receive message from client client_data = c.recv(1024) if not client_data: break decoded_msg = base64.b64decode(client_data).decode("utf-8") if decoded_msg.lower() == "exit": print("Client requested to close connection.") c.close() break print(f"Client: {decoded_msg}") # Only run server when script is executed directly if __name__ == "__main__": start_server()
Modified Client Script (Client.py)
import socket import base64 def start_client(): # Create a socket object s = socket.socket() # Define the port on which you want to connect port = 29759 # Connect to the server on local computer s.connect(('127.0.0.1', port)) print("Connected to server!") # Keep connection open for bidirectional messaging while True: # Receive message from server server_data = s.recv(1024) if not server_data: print("Server closed the connection.") break decoded_server_msg = base64.b64decode(server_data).decode("utf-8") if decoded_server_msg.lower() == "exit": print("Server closed the connection.") break print(f"Server: {decoded_server_msg}") # Send message to server client_msg = input("Enter your message (type 'exit' to close): ") encoded_msg = base64.b64encode(client_msg.encode("utf-8")) s.send(encoded_msg) if client_msg.lower() == "exit": print("Closing connection...") break # Close the connection s.close() if __name__ == "__main__": start_client()
Key Changes Explained
- Import Protection: The
if __name__ == "__main__":block ensures server/client logic only runs when the script is launched directly, not when imported. - Bidirectional Loop: Both scripts now have inner loops that handle sending and receiving messages until either side types
"exit". - Clean Decoding: Messages are properly decoded from base64 and converted to UTF-8 strings, so they print as readable text instead of byte objects.
How to Run
- First, run
Connection.pyto start the server. - Then run
Client.pyto connect to the server. - You can now send messages back and forth—type
"exit"in either terminal to close the connection.
内容的提问来源于stack exchange,提问作者KrulKracker

