Home > Backend Development > Python Tutorial > How Do I Access and Process Command Line Arguments in Python?

How Do I Access and Process Command Line Arguments in Python?

Patricia Arquette
Release: 2024-12-18 20:12:14
Original
373 people have browsed it

How Do I Access and Process Command Line Arguments in Python?

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:])
Copy after login

Explanation:

  • sys.argv is a list containing all the arguments passed to the script on the command line.
  • sys.argv[0] is the script name.
  • sys.argv[1:] contains all the arguments except the script name. This is useful for processing arguments that the script is expected to handle.

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) < 2:
    print("Usage: my_script.py <filename>")
    exit()

filename = sys.argv[1]

# Do something with the filename
Copy after login

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.

The above is the detailed content of How Do I Access and Process Command Line Arguments in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template