I wish to pass in some variables into python during run time
python add2values.py 123 124
then in the python script it will take those 2 values and add together.
OR
python add2values.py a=123 b=124
then in the python script it will take those 2 values and add together.
You can use sys.argv
test.py
#!/usr/bin/env python
import sys
total = int(sys.argv[1]) + int(sys.argv[2])
print('Argument List: %s' % str(sys.argv))
print('Total : %d' % total)
Run the following command:
$ python test.py 123 124
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Total : 247
There are a few ways to handle command-line arguments.
One is, as has been suggested, sys.argv: an array of strings from the arguments at command line. Use this if you want to perform arbitrary operations on different kinds of arguments. You can cast the first two arguments into integers and print their sum with the code below:
import sys
n1 = sys.argv[1]
n2 = sys.argv[2]
print (int(n1) + int(n2))
Of course, this does not check whether the user has input strings or lists or integers and gives the risk of a TypeError. However, for a range of command line arguments, this is probably your best bet - to manually take care of each case.
If your script/program has fixed arguments and you would like to have more flexibility (short options, long options, help texts) then it is worth checking out the optparse and argparse (requires Python 2.7 or later) modules. Below are some snippets of code involving these two modules taken from actual questions on this site.
import argparse
parser = argparse.ArgumentParser(description='my_program')
parser.add_argument('-verbosity', help='Verbosity', required=True)
optparse, usable with earlier versions of Python, has similar syntax:
from optparse import OptionParser
parser = OptionParser()
...
parser.add_option("-m", "--month", type="int",
help="Numeric value of the month",
dest="mon")
And there is even getopt if you prefer C-like syntax...
The argparse module allows you to write simple command line interfaces without much effort and is very flexible. It'll handle things like checking the input variables are of the right type that you specify and just make it easier to get on with writing your program.
The first example even demonstrates a similar program that will accept a list of strings to sum.
I think you mean passing parameter through command line argument. The code:
import sys
print int(sys.argv[1]) + int(sys.argv[2])
You can do this:
import sys
n1 = int(sys.argv[1])
n2 = int(sys.argv[2])
answer = n1 + n2
print answer
Use the sys module. This will add any arguments given:
import sys
print sum(map(int, sys.argv[1:]))
map() will have to be used because all elements in sys.argv are strings. We also have to slice the list because the first element will be the script name.
When run:
$ python myfile.py 123 124
247
$ python myfile.py 1 2 3
6
Related
I use python to create my project settings setup, but I need help getting the command line arguments.
I tried this on the terminal:
$python myfile.py var1 var2 var3
In my Python file, I want to use all variables that are input.
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
To get only the command line arguments
(not including the name of the Python file)
import sys
sys.argv[1:]
The [1:] is a slice starting from the second element (index 1) and going to the end of the arguments list. This is because the first element is the name of the Python file, and we want to remove that.
I highly recommend argparse which comes with Python 2.7 and later.
The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and the output for python prog.py 1 As one would expect:
2
Python code:
import sys
# main
param_1= sys.argv[1]
param_2= sys.argv[2]
param_3= sys.argv[3]
print 'Params=', param_1, param_2, param_3
Invocation:
$python myfile.py var1 var2 var3
Output:
Params= var1 var2 var3
You can use sys.argv to get the arguments as a list.
If you need to access individual elements, you can use
sys.argv[i]
where i is index, 0 will give you the python filename being executed. Any index after that are the arguments passed.
You can access arguments by key using "argparse".
Let's say that we have this command:
python main.py --product_id 1001028
To access the argument product_id, we need to declare it first and then get it:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--product_id', dest='product_id', type=str, help='Add product_id')
args = parser.parse_args()
print (args.product_id)
Output:
1001028
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0] which is always the current working directory.
Some additional things that I can think of.
As #allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.
Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html
First, You will need to import sys
sys - System-specific parameters and functions
This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.
And then, you can print the numbers of arguments or what you want here, the list of arguments.
Follow the script below :
#!/usr/bin/python
import sys
print 'Number of arguments entered :' len(sys.argv)
print 'Your argument list :' str(sys.argv)
Then, run your python script :
$ python arguments_List.py chocolate milk hot_Chocolate
And you will have the result that you were asking :
Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']
Hope that helped someone.
should use of sys ( system ) module .
the arguments has str type and are in an array
NOTICE : argv is not function or class and is variable & can change
NOTICE : argv[0] is file name
NOTICE : because python written in c , C have main(int argc , char *argv[]); but argc in sys module does not exits
NOTICE : sys module is named System and written in C that NOT A SOURCE BASED MODULE
from sys import argv # or
from sys import * # or
import sys
# code
print("is list") if type(sys.argv) == list else pass # is list ,or
print("is list") if type(argv) == list else pass # is list
# arguments are str ( string )
print(type(sys.argv[1])) # str
# command : python filename.py 1 2 3
print(len(sys.argv)) # 3
print(sys.argv[1],'\n',sys.argv[2]'\n',sys.argv[3]) # following
'''
1
2
3
'''
# command : python filename.py 123
print(len(sys.argv)) # 1
print(sys.argv[1]) # following
'''
123
'''
Using the following code, you can check whether the arguments are entered. If it is the case, the arguments are printed; otherwise, a message stating that the arguments are not entered is printed.
import sys
if len(sys.args) <= 1:
print("the arguments are not entered in the command line")
else:
for arg in args:
print(arg)
I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print ('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
You may have been directed here because you were asking about an IndexError in your code that uses sys.argv. The problem is not in your code; the problem is that you need to run the program in a way that makes sys.argv contain the right values. Please read the answers to understand how sys.argv works.
If you have read and understood the answers, and are still having problems on Windows, check if Python Script does not take sys.argv in Windows fixes the issue. If you are trying to run the program from inside an IDE, you may need IDE-specific help - please search, but first check if you can run the program successfully from the command line.
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.
sys.argv[1] contains the first command line argument passed to your script.
For example, if your script is named hello.py and you issue:
$ python3.1 hello.py foo
or:
$ chmod +x hello.py # make script executable
$ ./hello.py foo
Your script will print:
Hello there foo
sys.argv is a list.
This list is created by your command line, it's a list of your command line arguments.
For example:
in your command line you input something like this,
python3.2 file.py something
sys.argv will become a list ['file.py', 'something']
In this case sys.argv[1] = 'something'
Just adding to Frederic's answer, for example if you call your script as follows:
./myscript.py foo bar
sys.argv[0] would be "./myscript.py"
sys.argv[1] would be "foo" and
sys.argv[2] would be "bar" ... and so forth.
In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".
Adding a few more points to Jason's Answer :
For taking all user provided arguments: user_args = sys.argv[1:]
Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.
The syntax is like this: list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.
Suppose you only want to take all the arguments after 3rd argument, then:
user_args = sys.argv[3:]
Suppose you only want the first two arguments, then:
user_args = sys.argv[0:2] or user_args = sys.argv[:2]
Suppose you want arguments 2 to 4:
user_args = sys.argv[2:4]
Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step):
user_args = sys.argv[-1]
Suppose you want the second last argument:
user_args = sys.argv[-2]
Suppose you want the last two arguments:
user_args = sys.argv[-2:]
Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by :):
user_args = sys.argv[-2:]
Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item:
user_args = sys.argv[:-2]
Suppose you want the arguments in reverse order:
user_args = sys.argv[::-1]
sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.
To pass arguments to your python script
while running a script via command line
> python create_thumbnail.py test1.jpg test2.jpg
here,
script name - create_thumbnail.py,
argument 1 - test1.jpg,
argument 2 - test2.jpg
With in the create_thumbnail.py script i use
sys.argv[1:]
which give me the list of arguments i passed in command line as
['test1.jpg', 'test2.jpg']
sys.argv is a attribute of the sys module. It says the arguments passed into the file in the command line. sys.argv[0] catches the directory where the file is located. sys.argv[1] returns the first argument passed in the command line. Think like we have a example.py file.
example.py
import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument
Now here in the command prompt when we do this:
python example.py
It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code.
If we run the example.py with passing a argument
python example.py args
It prints:
args
Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:
example argumentpassed
It prints:
argumentpassed
It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.
sys.argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.
Just try this:
import sys
print sys.argv
argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.
Now try this running your filename.py like this:
python filename.py example example1
this will print 3 arguments in a list.
sys.argv[0] #is the first argument passed, which is basically the filename.
Similarly, argv[1] is the first argument passed, in this case 'example'.
My function convert.py is:
def convert(a,b)
factor = 2194.2
return (a-b)*factor
How do I run it from the command line with input arguments a and b?
I tried:
python convert.py 32 46
But got an error.
I did try to find the answer online, and I found related things but not the answer:
Run function from the command line (Stack Overflow)
How to read/process command line arguments? (Stack Overflow)
http://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/
http://www.saltycrane.com/blog/2007/12/how-to-pass-command-line-arguments-to/
Also, where can I find the answer myself so that I can save this site for more non-trivial questions?
You could do:
import sys
def convert(a,b):
factor = 2194.2
return (a-b)*factor
print(convert(int(sys.argv[1]), int(sys.argv[2])))
If that is all what should do the script, you dont have to define a function:
import sys
factor = 2194.2
print((int(sys.argv[1]), int(sys.argv[2])*factor)
If you want change your file (nonetheless you have to add the colon after the function definiton), you could follow your first linked approach:
python -c 'import convert, sys; print convert.convert(int(sys.argv[1]), int(sys.argv[2])'
There exists a Python module for this sort of thing called argparse, which allows you to do really fancy things around command line flags. You don't really need that - you've just got two numbers on the command line. This can be handled really naively.
Python allows you direct access to the command line arguments via an array called sys.argv - you'll need to import sys first. The first element in this array is always the program name, but the second and third will be the numbers you pass in i.e. sys.argv[1] and sys.argv[2]. For a more complete example:
if len(sys.argv) < 3:
print 'Didnt supply to numbers'
a = int(sys.argv[1])
b = int(sys.argv[2])
Of course you'll need some error checking around making sure they are actuall integers/floats.
A bit of extra reading around sys.argv if you're interested here
To be complete, we can give an argparse example as well:
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('numbers', type=float, nargs=2,
help='Things to perform actions on')
args = parser.parse_args()
a = args.numbers[0]
b = args.numbers[1]
print a, b
I use python to create my project settings setup, but I need help getting the command line arguments.
I tried this on the terminal:
$python myfile.py var1 var2 var3
In my Python file, I want to use all variables that are input.
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
To get only the command line arguments
(not including the name of the Python file)
import sys
sys.argv[1:]
The [1:] is a slice starting from the second element (index 1) and going to the end of the arguments list. This is because the first element is the name of the Python file, and we want to remove that.
I highly recommend argparse which comes with Python 2.7 and later.
The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and the output for python prog.py 1 As one would expect:
2
Python code:
import sys
# main
param_1= sys.argv[1]
param_2= sys.argv[2]
param_3= sys.argv[3]
print 'Params=', param_1, param_2, param_3
Invocation:
$python myfile.py var1 var2 var3
Output:
Params= var1 var2 var3
You can use sys.argv to get the arguments as a list.
If you need to access individual elements, you can use
sys.argv[i]
where i is index, 0 will give you the python filename being executed. Any index after that are the arguments passed.
You can access arguments by key using "argparse".
Let's say that we have this command:
python main.py --product_id 1001028
To access the argument product_id, we need to declare it first and then get it:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--product_id', dest='product_id', type=str, help='Add product_id')
args = parser.parse_args()
print (args.product_id)
Output:
1001028
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0] which is always the current working directory.
Some additional things that I can think of.
As #allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.
Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html
First, You will need to import sys
sys - System-specific parameters and functions
This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.
And then, you can print the numbers of arguments or what you want here, the list of arguments.
Follow the script below :
#!/usr/bin/python
import sys
print 'Number of arguments entered :' len(sys.argv)
print 'Your argument list :' str(sys.argv)
Then, run your python script :
$ python arguments_List.py chocolate milk hot_Chocolate
And you will have the result that you were asking :
Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']
Hope that helped someone.
should use of sys ( system ) module .
the arguments has str type and are in an array
NOTICE : argv is not function or class and is variable & can change
NOTICE : argv[0] is file name
NOTICE : because python written in c , C have main(int argc , char *argv[]); but argc in sys module does not exits
NOTICE : sys module is named System and written in C that NOT A SOURCE BASED MODULE
from sys import argv # or
from sys import * # or
import sys
# code
print("is list") if type(sys.argv) == list else pass # is list ,or
print("is list") if type(argv) == list else pass # is list
# arguments are str ( string )
print(type(sys.argv[1])) # str
# command : python filename.py 1 2 3
print(len(sys.argv)) # 3
print(sys.argv[1],'\n',sys.argv[2]'\n',sys.argv[3]) # following
'''
1
2
3
'''
# command : python filename.py 123
print(len(sys.argv)) # 1
print(sys.argv[1]) # following
'''
123
'''
Using the following code, you can check whether the arguments are entered. If it is the case, the arguments are printed; otherwise, a message stating that the arguments are not entered is printed.
import sys
if len(sys.args) <= 1:
print("the arguments are not entered in the command line")
else:
for arg in args:
print(arg)
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed last month.
What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?
I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:
if 'debug' in argv[1:]:
print 'Will be running in debug mode.'
How to find out if 009 or 575 was passed?
All those are expected calls:
python script.py
python script.py 011
python script.py 256 debug
python script.py 391 xls
python script.py 999 debug pdf
At this point I don't care about calls like that:
python script.py 001 002 245 568
python script.py some unexpected argument
python script.py 0001
python script.py 02
...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.
As others answered, optparse is the best option, but if you just want quick code try something like this:
import sys, re
first_re = re.compile(r'^\d{3}$')
if len(sys.argv) > 1:
if first_re.match(sys.argv[1]):
print "Primary argument is : ", sys.argv[1]
else:
raise ValueError("First argument should be ...")
args = sys.argv[2:]
else:
args = ()
# ... anywhere in code ...
if 'debug' in args:
print 'debug flag'
if 'xls' in args:
print 'xls flag'
EDIT: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.
The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.
So here's an example using optparse:
import sys, re, optparse
first_re = re.compile(r'^\d{3}$')
parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()
if len(args) == 1:
if first_re.match(args[0]):
print "Primary argument is : ", args[0]
else:
raise ValueError("First argument should be ...")
elif len(args) > 1:
raise ValueError("Too many command line arguments")
if options.debug:
print 'debug flag'
if options.xls:
print 'xls flag'
The differences here with optparse and your spec is that now you can have command lines like:
python script.py --debug --xls 001
and you can easily add new options by calling parser.add_option()
Have a look at the optparse module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.
Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace debug with --debug and xls with --xls or --output=xls.
optparse is your best friend for parsing the command line. Also look into argparse; it's not in the standard library, though.
If you want to implement actual command line switches, give getopt a look. It's incredibly simple to use, too.
Van Gale is largely correct in using the regular expression against the argument. However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a "-" or "--" is in front or not. Some example code to go through just the arguments:
import sys
import optparse
claParser = optparse.OptionParser()
claParser.add_option(
(opts, args) = claParser.parse_args()
if (len(args) >= 1):
print "Arguments:"
for arg in args:
print " " + arg
else:
print "No arguments"
sys.exit(0)
Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added. For more about optparse, check out the relevant Python doc.