Reputation: 1313
New to Python and started from the documentation linearly: https://docs.python.org/3.7/library/sys.html
If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
My code:
import sys
print(sys.argv)
My command:
py main.py -c test
Output:
['main.py', '-c', 'test']
So it appears even tho I entered -c test sys.argv[0] value is 'main.py', while documentation states it should be '-c'.
So '-c' here is actually sys.argv[1].
Python version: 3.7.3.
Am I misunderstanding something?
Upvotes: 0
Views: 1004
Reputation: 455
That is because the option -c
needs to be in first position.
I tried to create a simple script test.py
:
print('foo')
If you run python test.py test.py
, you will see only one foo
, which means the second test.py
gets ignored. This is the same for your example py main.py -c test
This is not very clear in the documentation, but I think this the spirit:
2.1.1. Argument Passing
When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the argv variable in the sys module. You can access this list by executing import sys. The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.
So the correct usage is python -c "cmd"
and not python file.py -c file2.py
.
Upvotes: 1
Reputation: 1313
A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) in command.
-c is not passing the '-c' string to the program as argument, it's executing a statement in the command, by example:
python -c "import sys; print(sys.argv)"
In sys.argv first value is always name of executed python module, either the filename or command.
Upvotes: 0