Python: sys.argv [0] value in official documentation

Quote from docs.python.org :

" sys.argv list of command line arguments passed to the Python script. argv[0] is the name of the script (it depends on the operating system whether it is the full path name or not). If the command was executed using the -c command line parameter to the interpreter , argv[0] set to the string '-c' . If the script name was not passed to the Python interpreter, argv[0] is the empty string. "

Am I missing something, or sys.argv[0] always return the name of the script, but will I need to use sys.argv[1] to get '-c' ?

I am testing Python 3.2 on GNU / Linux.

+4
source share
3 answers

No, if you call Python using -c to run commands from the command line, your sys.argv[0] will be -c :

 C:\Python27>python.exe -c "import sys; print sys.argv[0]" -c 
+10
source

When Python is called as python script.py , then sys.argv[0] == 'script.py' . When you call python -c 'import sys; print sys.argv' python -c 'import sys; print sys.argv' , then sys.argv[0] == '-c' indicates that the body of the script is passed as a string on the command line.

+4
source

python -c executes the command passed on the command line, not the script from the file. sys.argv[0] will be set to "-c" .

If you run the script with the -c flag, then yes, sys.argv[1] will be set to "-c" and sys.argv[0] script name will be set.

0
source

Source: https://habr.com/ru/post/1342665/


All Articles