Python

Get parameter from command line in Python (sys.argv)

Get parameter from command line in Python (sys.argv)

Get parameter from command line in Python.

If you run a Python file with several settings, command line parameter is helpful.
You can also pass variables from outside.
This article introduce how to pass parameters from command line.



What is command line ?

Command line is a system that you can control PC or server with command.
In Windows, it is known as black window or command prompt .
In Mac, it is called Terminal .


How to pass parameters from command line

In oreder to pass parameters from command line to Python, you can use sys.argv.

[python title="commandline-var.py"]
import sys

args = sys.argv
for v in args:
print(v)
[/python]

You can run it like python (file name) parameter1 parameter2 parameter3... .

[python title="Run"]
python commandline-var.py a b c
[/python]

As you can see the result, parameter0 is file itself.

[python title="Result"]
commandline-var.py
a
b
c
[/python]

Reference
Recaive command line parameter in Python - Qiita


Finally

  • In oreder to pass parameters from command line to Python, you can use sys.argv.


If you felt this article is useful, please share.

にほんブログ村 IT技術ブログへ

-Python

© 2024 ITips