Processing Command Line Arguments in Python
In Python, the command line arguments are available in a list called sys.argv. To access these arguments, use the following syntax:
import sys # Print all command line arguments print("\n".join(sys.argv)) # Print all arguments except the script name print(sys.argv[1:])
Explanation:
Example:
Let's say we have a script called my_script.py that takes a filename as an argument. We can process this argument using the following code:
import sys if len(sys.argv) ") exit() filename = sys.argv[1] # Do something with the filename
This code checks if the user has provided a filename and exits gracefully if not. Otherwise, it assigns the filename to a variable for further processing.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3