Python Glossary Русский

all Python 3systerm

sys.argv

arguments

The list of command-line arguments. sys.argv[0] is the script name, the rest are the arguments passed to it.

Syntax

sys.argv  # list[str]

Every element is a string, even "10", so anything arithmetic needs int() or float() first. Touching sys.argv[1] without checking len(sys.argv) is the classic IndexError you get the moment the script is run with no arguments. sys.argv[0] itself depends on how Python was started (it is '-c' under python -c, and an empty string when the code comes from stdin), and once you have more than a couple of flags, parse them with argparse rather than by hand.

Examples

import sys
sys.argv = ['script.py', 'arg1', 'arg2']  # так его заполнит: python script.py arg1 arg2
print(sys.argv)  # → ['script.py', 'arg1', 'arg2'] — первым идёт имя скрипта
for arg in sys.argv[1:]:
    print(arg)  # → arg1 / arg2
print(len(sys.argv) - 1)  # → 2 — число аргументов без имени скрипта

See also

Open in the full glossarydocs.python.orgReport an inaccuracy