Python network programming - get terminal command line parameters

Introduction: Get terminal command line arguments by using sys.argv

【Python get terminal command line parameters】Overview


Get terminal command line arguments by using sys.argv


【Python get terminal command line parameters】Implementation steps


1. Import the sys module
import sys

2. Get command line parameters
params = sys.argv _ _
print ( params )
print ( params [ 1 ])
The obtained string type may need to be converted before use


【Python get terminal command line parameters】The command line starts the dynamic binding port number


1. Get the terminal command line parameters for executing the python program
sys.argv _ _

2. Determine the type of the parameter, set the port number must be an integer
if not sys.argv [ 1 ] .isdigit ( ) :
print ( "The startup command is as follows: python3 xxx.py 9090" )
return
port = int ( sys.argv [ 1 ] ) _

3. Add a port number parameter to the initialization method of the Web server class to bind the port number
def __init__ ( self , port ):
self . tcp_server_socket . bind (( "" , port ))

Code
import socket
import threading
import sys


# Define the web server class
class HttpWebServer ( object ):
def __init__ ( self , port ):
# create tcp server socket
tcp_server_socket = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) _ _ _ _ _ _
# Set the port number multiplexing, the program exits the port and releases it immediately
tcp_server_socket.setsockopt ( socket.SOL_SOCKET , socket.SO_REUSEADDR , True ) _ _ _ _ _ _
# bind port number
tcp_server_socket.bind ( ( "" , port ) )
# set monitor
tcp_server_socket.listen ( 128 ) _ _
# Save the successfully created server socket
self.tcp_server_socket _ _ = tcp_server_socket

# handle client requests
@staticmethod
def handle_client_request ( new_socket ):
# The code is executed here, indicating that the connection is successfully established
recv_client_data = new_socket.recv ( 4096 ) _ _
if len ( recv_client_data ) == 0 :
print ( "close the browser" )
new_socket.close ( ) _
return

# decode binary data
recv_client_content = recv_client_data.decode ( " utf -8" )
print ( recv_client_content )
# Split according to the specified string, the maximum number of splits is specified as 2
request_list = recv_client_content.split ( " " , maxsplit = 2 ) _

# Get the request resource path
request_path = request_list [ 1 ]
print ( request_path )

# Determine whether the request is the root directory, if the condition is true, specify the home page data to return
if request_path == "/" :
request_path = "/index.html"

try :
# Dynamically open the specified file
with open ( "static" + request_path , "rb" ) as file :
# read file data
file_data = file.read ( ) _
except Exception as e :
# The requested resource does not exist, return 404 data
# response line
response_line = "HTTP/1.1 404 Not Found "
# response header
response_header = "Server: PWS1.0 "
with open ( "static/error.html" , "rb" ) as file :
file_data = file.read ( ) _
# response body
response_body = file_data

# Concatenate the response message
response_data = ( response_line + response_header + " " ) .encode ( "utf-8" ) + response_body
# send data
new_socket.send ( response_data ) _ _
else :
# response line
response_line = "HTTP/1.1 200 OK "
# response header
response_header = "Server: PWS1.0 "

# response body
response_body = file_data

# Concatenate the response message
response_data = ( response_line + response_header + " " ) .encode ( "utf-8" ) + response_body
# send data
new_socket.send ( response_data ) _ _
finally :
# Close the socket between the service and the client
new_socket.close ( ) _

# Start the web server to work
def start ( self ):
while True :
# Waiting to accept the connection request from the client
new_socket , ip_port = self.tcp_server_socket.accept ( ) _ _ _
# When the client and the server establish a connection process, create a child thread
sub_thread = threading . Thread ( target = self . handle_client_request , args = ( new_socket ,))
# Set the daemon main thread
sub_thread.setDaemon ( True ) _ _
# Start the child thread to execute the corresponding task
sub_thread.start ( ) _


# Program entry function
def main ():

print ( sys.argv ) _ _
# Determine if the command line parameter is equal to 2,
if len ( sys . argv ) != 2 :
print ( "Execute the command as follows: python3 xxx.py 8000" )
return

# Determine if the string is composed of numbers
if not sys.argv [ 1 ] .isdigit ( ) :
print ( "Execute the command as follows: python3 xxx.py 8000" )
return

# Get terminal command line parameters
port = int ( sys.argv [ 1 ] ) _
# Create web server object
web_server = HttpWebServer ( port )
# Start the web server to work
web_server.start ( ) _


if __name__ == '__main__' :
main ()
Copyright statement: The content of this article is contributed by Alibaba Cloud's real-name registered users. The copyright belongs to the original author. The Alibaba Cloud developer community does not own the copyright and does not assume the corresponding legal responsibility. For specific rules, please refer to the " Alibaba Cloud Developer Community User Service Agreement " and " Alibaba Cloud Developer Community Intellectual Property Protection Guidelines ". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00