Skip to content
shellhacks.dev
Python

Read Command-Line Arguments in Python with sys.argv

Read arguments with sys.argv, a list of strings where item 0 is the script name. The shell expands globs first, and Python keeps a lone -- as a normal item.

1 min read
Summarize in AI

A script should take values from the command line, and you want to see exactly what Python receives.

Shell
cat > show.py <<'EOF'
import sys
print(sys.argv)
EOF
python3 show.py
python3 show.py one 'two words' --flag=3 -- x
touch a.txt b.txt
python3 show.py *.txt
python3 -c 'import sys; print(sys.argv)' a b
Text
['show.py']
['show.py', 'one', 'two words', '--flag=3', '--', 'x']
['show.py', 'a.txt', 'b.txt']
['-c', 'a', 'b']

sys.argv[0] is the script as it was typed and everything after it is a string, so numbers must be converted. The run shows that quoting survives, since 'two words' arrived as one item, that *.txt was expanded by the shell into a.txt and b.txt before Python started, and that -- is passed through as an ordinary item. With -c the first item is -c. See sys.argv.

sys.argv does no parsing or validation, so anything beyond one or two positional values is better served by argparse. Python 3 decodes arguments with the file system encoding, and bytes that are not valid there are carried as surrogate escapes, which can fail on output.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.