What does sys.argv[1] mean?
I would like to note that previous answers made many assumptions about the user's knowledge. This answer attempts to answer the question at a more tutorial level.
For every invocation of Python, sys.argv
is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The name comes from the C programming convention in which argv and argc represent the command line arguments.
You'll want to learn more about lists and strings as you're familiarizing yourself with Python, but in the meantime, here are a few things to know.
You can simply create a script that prints the arguments as they're represented. It also prints the number of arguments, using the len
function on the list.
from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))
The script requires Python 2.6 or later. If you call this script print_args.py
, you can invoke it with different arguments to see what happens.
> python print_args.py
['print_args.py'] 1
> python print_args.py foo and bar
['print_args.py', 'foo', 'and', 'bar'] 4
> python print_args.py "foo and bar"
['print_args.py', 'foo and bar'] 2
> python print_args.py "foo and bar" and baz
['print_args.py', 'foo and bar', 'and', 'baz'] 4
As you can see, the command-line arguments include the script name but not the interpreter name. In this sense, Python treats the script as the executable. If you need to know the name of the executable (python in this case), you can use sys.executable
.
You can see from the examples that it is possible to receive arguments that do contain spaces if the user invoked the script with arguments encapsulated in quotes, so what you get is the list of arguments as supplied by the user.
Now in your Python code, you can use this list of strings as input to your program. Since lists are indexed by zero-based integers, you can get the individual items using the list[0] syntax. For example, to get the script name:
script_name = sys.argv[0] # this will always work.
Although interesting, you rarely need to know your script name. To get the first argument after the script for a filename, you could do the following:
filename = sys.argv[1]
This is a very common usage, but note that it will fail with an IndexError if no argument was supplied.
Also, Python lets you reference a slice of a list, so to get another list of just the user-supplied arguments (but without the script name), you can do
user_args = sys.argv[1:] # get everything after the script name
Additionally, Python allows you to assign a sequence of items (including lists) to variable names. So if you expect the user to always supply two arguments, you can assign those arguments (as strings) to two variables:
user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2
So, to answer your specific question, sys.argv[1]
represents the first command-line argument (as a string
) supplied to the script in question. It will not prompt for input, but it will fail with an IndexError if no arguments are supplied on the command-line following the script name.
What is Python first argument? sys.argv[0] or sys.argv[1]
sys.argv[0]
is the name of the script. Technically it is the "first" argument, but is typically of no use to you, unless you don't know the name of the file you're executing. sys.argv[1]
, is the name of the first argument after the name of the script, so the first useful argument.
sys.argv[1][-4:] script meaning
Whenever running a Python program, sys.argv
is automatically a list of strings representing the arguments mentioned when running the program.
Using sys.argv[1]
is therefore the same as looking at the first element of a list, and more precisely the first argument provided when running the Python program. From how Python works, it will always be a string.
So if in script you were to do:
python helloworld.py file1.txt file2.jpg
And your program contained sys.argv[1]
, you could see:
print(sys.argv[1])
# > "file1.txt"
Now, since sys.argv[1]
is a string, doing sys.argv[1][-4:] is just looking at the four last characters of the string contained in sys.argv[1]
, so you would have:
print(sys.argv[1][-4:])
# > ".txt"
So to sum it up, all your code does is checking that the extension of the file mentioned in the first argument when running your program is .dfa, or, in other words, that the file name that you mentioned as first argument ends with ".dfa"
.
python sys.argv[1] vs. sys.argv[1:]
sys.argv
is a list of arguments.
So when you execute your script without any arguments this list which you're accessing index 1 of is empty and accessing an index of an empty list will raise an IndexError
.
With your second block of code you're doing a list slice and you're checking if the list slice from index 1 and forward is not empty then print your that slice of the list.
Why this works is because if you have an empty list and doing a slice on it like this, the slice returns an empty list.
last_list = [1,2,3]
if last_list[1:]:
print last_list[1:]
>> [2,3]
empty_list = []
print empty_list[:1]
>> []
handling an empty (sys.argv[1])
sys.argv
is a list that contains the program's arguments, with sys.argv[0]
being the name of the script itself.
The way to count how many arguments there are is to check the length of sys.argv
, not of sys.argv[1]
.
You also need to do this before trying to access sys.argv[1]
, since it might not exist:
import sys
if len(sys.argv) < 2:
print(round(volume.value_flat, 2))
exit(0)
vol = float(sys.argv[1])
# run the rest of the program
manually setting sys.argv[1] within script
TL;DR Don't use sys.argv
; use argparse
.
What you are doing now doesn't require setting sys.argv[1]
; just use "DEFAULT"
where you would have used it.
if len(sys.argv) == 1:
print('Using DEFAULT'):
ASDF = config.get('DEFAULT', 'ASDF');
BSDF = config.get('DEFAULT', 'BSDF');
elif len(sys.argv) == 2:
print('Using ' + sys.argv[1]):
ASDF = config.get(sys.argv[1],'ASDF');
BSDF = config.get(sys.argv[1],'BSDF');
else:
print('too many inputs, don''t confuse me...')
sys.exit(1)
Setting sys.argv[1]
is useful if you want to factor out the calls to config.get
, for example,
if len(sys.argv) == 1:
# there is no sys.argv[1] to assign to;
# you need to append to the list.
sys.argv.append('DEFAULT')
elif len(sys.argv) > 2:
sys.exit(1)
print('Using ' + sys.argv[1]):
ASDF = config.get(sys.argv[1],'ASDF');
BSDF = config.get(sys.argv[1],'BSDF');
That said, in general, you don't use sys.argv
directly. Use argparse
as in QuantumLicht's answer.
How to use sys.argv?
What you need here is called COMMAND LINE ARGUMENTS.
here's a way to implement it.
import sys
first_arg = sys.argv[1]
second_arg = sys.argv[2]
the first_args will hold whatever the first parameter is passed to the script and so on.
sys.argv is a list of parameters provided to the python interpreter. sys.argv[0] will always be the file name.
sys.argv[1], IndexError: list index out of range
sys.argv
represents the command line options you execute a script with.
sys.argv[0]
is the name of the script you are running. All additional options are contained in sys.argv[1:]
.
You are attempting to open a file that uses sys.argv[1]
(the first argument) as what looks to be the directory.
Try running something like this:
python ConcatenateFiles.py /tmp
Related Topics
Regular Expression to Return Text Between Parenthesis
Regular Expression to Match a Dot
Pip Install MySQL-Python Fails with Environmenterror: MySQL_Config Not Found
Is There a Simple Way to Delete a List Element by Value
Tensorflow Not Found Using Pip
Import Error: No Module Name Urllib2
Run Certain Code Every N Seconds
Else Clause on Python While Statement
Pycharm Shows Unresolved References Error for Valid Code
Matplotlib Scatterplot; Color as a Function of a Third Variable
Get a Variable from the Url in a Flask Route
How to Call a Python Function from Node.Js
Python's Time.Clock() VS. Time.Time() Accuracy
How to Specify Multiple Return Types Using Type-Hints
Dynamically Updating Plot in Matplotlib
Access Multiple Elements of List Knowing Their Index
Lxml Error "Ioerror: Error Reading File" When Parsing Facebook Mobile in a Python Scraper Script