How to receive command line arguments in Python

What are command line arguments?

A command line argument is a character string specified when starting a program from the command input screen (command line) of a computer. Also, the value of the variable etc. that received this on the program side.

http://e-words.jp/w/%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%83%A9%E3%82%A4%E3%83%B3%E5%BC%95%E6%95%B0.html

Command line arguments are the arguments of the main function. You can give values to command line arguments from the command line when you run it.

http://www.ritsumei.ac.jp/~mmr14135/johoWeb/cmnds.html

>>> ls -a
↑ here

Receive command line arguments in Python

There are three main ways to receive command line arguments in Python.

  1. Use sys.argv
  2. Use ʻargparse`
  3. Use click

is.

sys.argv

This is the most recognized (I think) method. Get it using sys, the Python standard library.

args.py


import sys


def main() -> None:
    args = sys.argv
    print(args)


if __name__=='__main__':
    main()

Run

>>> python args.py aaa 123 hoge
['args.py', 'aaa', '123', 'hoge']
merit デmerit
Easy to write I don't know what type will come
Python standard library No help

argparse

A Python standard library dedicated to command line arguments. You can specify the Help function and type. There is a habit of handling.

args2.py


import argparse


def main() -> None:
    parser = argparse.ArgumentParser(description='Description')

    parser.add_argument('description', help='Argument description')  #If not specified at runtime, an error will occur.
    parser.add_argument('hoge', help='hogehoge')  #The order is fixed.
    parser.add_argument('--foo', help='option')  #1 hyphen~If you attach two, you do not have to specify it at runtime.

    args = parser.parse_args()

    print(args.description)
    print(args.hoge)
    print(args.foo)


if __name__ == "__main__":
    main()

Run

>>> python args2.py -h
usage: aaa.py [-h] [--foo FOO] description hoge

Description

positional arguments:
description Argument description
  hoge         hogehoge

optional arguments:
  -h, --help   show this help message and exit
  --foo FOO    option

>>> python args2.py aaa bbb
aaa
bbb
None

>>> python args2.py aaa bbb --foo 123
aaa
bbb
123
merit デmerit
Rich in features complexity
There is help
Python standard library

click

Python command line parser. In other words, a module for command line analysis. Since it is not a Python standard library, it needs to be installed separately, but the above two are omitted for ease of understanding and usability. Therefore, it is OK if you remember this By the way, click, Flask, and jinja are same project.

#Installation
pip install click

args3.py


import click


@click.command()
@click.option('--args', prompt=True, help='Description')
@click.option('--hoge', prompt=True, is_flag=True, help='hogehoge')
def main(args: str, hoge: bool) -> None:
    if hoge:
        print(args)


if __name__ == "__main__":
    main()

Run

>>> python args3.py --args foo --hoge
foo

>>> python args3.py
Args: aaaaa
Hoge [y/N]: y
aaaaa
merit デmerit
Rich in features Not a Python standard library
Easy to use
Can be displayed at the prompt
You can also display the progress bar
You can hide your password entry
Multiple inputs are possible

Reference material

How to handle command line arguments in Python (sys.argv, argparse) [How to pass command line arguments in Python](https://intellectual-curiosity.tokyo/2018/12/14/python%E3%81%A7%E3%82%B3%E3%83%9E%E3%83 % B3% E3% 83% 89% E3% 83% A9% E3% 82% A4% E3% 83% B3% E5% BC% 95% E6% 95% B0% E3% 82% 92% E6% B8% A1 % E3% 81% 99% E6% 96% B9% E6% B3% 95 /) A brief summary of how to use ArgumentParser Python: Click on the command line parser was too convenient

Recommended Posts

How to receive command line arguments in Python
How to specify command line arguments when debugging in PyCharm
[Python / Tkinter] How to pass arguments to command
Decompose command arguments in one line in Python
How to get a string from a command line argument in python
[Python] How to test command line parser click
How to implement Discord Slash Command in Python
[Introduction to Udemy Python3 + Application] 67. Command line arguments
Receive runtime arguments in Python 2.7
How to develop in Python
[For beginners] How to use say command in python!
How to execute a command using subprocess in Python
[Python] How to do PCA in Python
How to collect images in Python
How to use SQLite in Python
In the python command python points to python3.8
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to manage arguments when implementing a Python script as a command line tool
How to handle Japanese in Python
How to pass arguments when invoking python script from blender on the command line
[Introduction to Python] How to use class in Python?
How to access environment variables in Python
How to dynamically define variables in Python
How to do R chartr () in Python
[Itertools.permutations] How to put permutations in Python
[python] How to use __command__, function explanation
How to work with BigQuery in Python
How to get a stacktrace in python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to use regular expressions in Python
How to display Hello world in python
How to use is and == in Python
How to write Ruby to_s in Python
How to pass arguments to a Python script in SPSS Modeler Batch
python Note: Determine if command line arguments are in the list
Template for creating command line applications in Python
How to use the C library in Python
Automatically register function arguments to argparse in Python
[REAPER] How to play with Reascript in Python
How to clear tuples in a list (Python)
How to install Python
How to generate permutations in Python and C ++
How to embed a variable in a python string
How to hide the command prompt when running python in visual studio 2015
Summary of how to import files in Python 3
Let's understand how to pass arguments (Python version)
How to simplify restricted polynomial fit in python
How to use Python Image Library in python3 series
How to implement shared memory in Python (mmap.mmap)
How to create a JSON file in Python
How to install python
Summary of how to use MNIST in Python