logo

How to Pass Arguments When Executing a Python File 📂Programing

How to Pass Arguments When Executing a Python File

Code

To pass arguments to a Python file when executing, you just need to input the path to the Python file followed by the arguments separated by spaces. If you want to pass the variables 1, x, “3”, and 3 to a Python file named text.py, you would enter the following in the command line:

python test.py 1 x "3" 3

To use the passed arguments inside the Python file, the standard library sys is used. sys.argv is a list that contains the arguments entered in the command line as strings. The first element is the path to the Python file, and the elements that follow are the arguments passed. Regardless of whether quotes are used, all arguments are passed as strings. If you write and execute the test.py file as follows,

# 테스트 파일 작성
import sys

print("sys.argv:", sys.argv)
print("type of sys.argv:", type(sys.argv))

for i, arg in enumerate(sys.argv):
    print("sys.argv[{}]:".format(i), arg, ", type:", type(arg))

print("sys.argv[3] == sys.argv[4]:", sys.argv[3] == sys.argv[4])

# 콘솔창에서 실행
>python test.py 1 x 3 "3"

sys.argv: ['test.py', '1', 'x', '3', '3']
type of sys.argv: <class 'list'>

sys.argv[0]: test.py , type: <class 'str'>
sys.argv[1]: 1 , type: <class 'str'>
sys.argv[2]: x , type: <class 'str'>
sys.argv[3]: 3 , type: <class 'str'>
sys.argv[4]: 3 , type: <class 'str'>
sys.argv[3] == sys.argv[4]: True

For more advanced features, you can use the argparse library.

Environment

  • OS: Windows11
  • Version: Python 3.9.13