This worked for me:
import sys
firstarg=sys.argv[1]
secondarg=sys.argv[2]
thirdarg=sys.argv[3]
Answer from Peter Gerhat on Stack ExchangeThis worked for me:
import sys
firstarg=sys.argv[1]
secondarg=sys.argv[2]
thirdarg=sys.argv[3]
You can use the argv from sys
from sys import argv
arg1, arg2, arg3, ... = argv
You can actually put an abitrary number of arguments in the command line. argv will be a list with the arguments. Thus it can also be called as arg1 = sys.argv[0] arg2 = sys.argv[1] . . .
Keep also in mind that sys.argv[0] is simply the name of your python program. Additionally, the "eval" and "exec" functions are nice when you use command line input. Usually, everything in the command line is interpreted as a string. So, if you want to give a formula in the command line you use eval().
>>> x = 1
>>> print eval('x+1')
2
Pass arguments from cmd to python script - Stack Overflow
command line - Python file keyword argument? - Stack Overflow
Passing argument to function from command line
Argument passing in python script
Videos
You can use the Optional Arguments like so.
With this program:
#!/usr/bin/env python3
import argparse, sys
parser=argparse.ArgumentParser()
parser.add_argument("--bar", help="Do the bar option")
parser.add_argument("--foo", help="Foo the program")
args=parser.parse_args()
print(f"Args: {args}\nCommand Line: {sys.argv}\nfoo: {args.foo}")
print(f"Dict format: {vars(args)}")
Make it executable:
$ chmod +x prog.py
Then if you call it with:
$ ./prog.py --bar=bar-val --foo foo-val
It prints:
Args: Namespace(bar='bar-val', foo='foo-val')
Command Line: ['./prog.py', '--bar=bar-val', '--foo', 'foo-val']
foo: foo-val
Dict format: {'bar': 'bar-val', 'foo': 'foo-val'}
Or, if the user wants help argparse builds that too:
$ ./prog.py -h
usage: prog.py [-h] [--bar BAR] [--foo FOO]
options:
-h, --help show this help message and exit
--bar BAR Do the bar option
--foo FOO Foo the program
2022-08-30: Updated to Python3 this answer...
The answer is yes. A quick look at the argparse documentation would have answered as well.
Here is a very simple example, argparse is able to handle far more specific needs.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', help="a random options", type= str)
parser.add_argument('--bar', '-b', help="a more random option", type= int, default= 0)
print(parser.format_help())
# usage: test_args_4.py [-h] [--foo FOO] [--bar BAR]
#
# optional arguments:
# -h, --help show this help message and exit
# --foo FOO, -f FOO a random options
# --bar BAR, -b BAR a more random option
args = parser.parse_args("--foo pouet".split())
print(args) # Namespace(bar=0, foo='pouet')
print(args.foo) # pouet
print(args.bar) # 0
Off course, in a real script, you won't hard-code the command-line options and will call parser.parse_args() (without argument) instead. It will make argparse take the sys.args list as command-line arguments.
You will be able to call this script this way:
test_args_4.py -h # prints the help message
test_args_4.py -f pouet # foo="pouet", bar=0 (default value)
test_args_4.py -b 42 # foo=None, bar=42
test_args_4.py -b 77 -f knock # foo="knock", bar=77
You will discover a lot of other features by reading the doc ;)
There are a few modules specialized in parsing command line arguments: getopt, optparse and argparse. optparse is deprecated, and getopt is less powerful than argparse, so I advise you to use the latter, it'll be more helpful in the long run.
Here's a short example:
import argparse
# Define the parser
parser = argparse.ArgumentParser(description='Short sample app')
# Declare an argument (`--algo`), saying that the
# corresponding value should be stored in the `algo`
# field, and using a default value if the argument
# isn't given
parser.add_argument('--algo', action="store", dest='algo', default=0)
# Now, parse the command line arguments and store the
# values in the `args` variable
args = parser.parse_args()
# Individual arguments can be accessed as attributes...
print args.algo
That should get you started. At worst, there's plenty of documentation available on line (say, this one for example)...
It might not answer your question, but some people might find it usefull (I was looking for this here):
How to send 2 args (arg1 + arg2) from cmd to python 3:
----- Send the args in test.cmd:
python "C:\Users\test.pyw" "arg1" "arg2"
----- Retrieve the args in test.py:
import sys, getopt
print ("This is the name of the script= ", sys.argv[0])
print("Number of arguments= ", len(sys.argv))
print("all args= ", str(sys.argv))
print("arg1= ", sys.argv[1])
print("arg2= ", sys.argv[2])
You can also use the sys module. Here is an example :
import sys
first_arg = sys.argv[1]
second_arg = sys.argv[2]
def greetings(word1=first_arg, word2=second_arg):
print("{} {}".format(word1, word2))
if __name__ == "__main__":
greetings()
greetings("Bonjour", "monde")
It has the behavior your are looking for :
$ python parse_args.py Hello world
Hello world
Bonjour monde
Python provides more than one way to parse arguments. The best choice is using the argparse module, which has many features you can use.
So you have to parse arguments in your code and try to catch and fetch the arguments inside your code.
You can't just pass arguments through terminal without parsing them from your code.