This is my python hello.py script:
def hello(a,b):
print "hello and that's your sum:"
sum=a+b
print sum
import sys
if __name__ == "__main__":
hello(sys.argv[2])
The problem is that it can't be run from the windows command line prompt, I used this command:
C:\Python27>hello 1 1
But it didn't work unfortunately, may somebody please help?
import sys out of hello function.
arguments should be converted to int.
String literal that contain ' should be escaped or should be surrouned by ".
Did you invoke the program with python hello.py <some-number> <some-number> in command line?
import sys
def hello(a,b):
print "hello and that's your sum:", a + b
if __name__ == "__main__":
a = int(sys.argv[1])
b = int(sys.argv[2])
hello(a, b)
I found this thread looking for information about dealing with parameters; this easy guide was so cool:
import argparse
parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")
args = parser.parse_args()
opt1_value = args.opt1
opt2_value = args.opt2
runs like:
python myScript.py --opt2 = 'hi'
Here are all of the previous answers summarized:
modules should be imported outside of functions.
hello(sys.argv[2]) needs to be indented since it is inside an if statement.
hello has 2 arguments so you need to call 2 arguments.
as far as calling the function from terminal, you need to call python .py ...
The code should look like this:
import sys
def hello(a, b):
print "hello and that's your sum:"
sum = a+b
print sum
if __name__== "__main__":
hello(int(sys.argv[1]), int(sys.argv[2]))
Then run the code with this command:
python hello.py 1 1
To execute your program from the command line, you have to call the python interpreter, like this :
C:\Python27>python hello.py 1 1
If you code resides in another directory, you will have to set the python binary path in your PATH environment variable, to be able to run it, too. You can find detailed instructions here.
Your indentation is broken. This should fix it:
import sys
def hello(a,b):
print 'hello and thats your sum:'
sum=a+b
print sum
if __name__ == "__main__":
hello(sys.argv[1], sys.argv[2])
Obviously, if you put the if __name__ statement inside the function, it will only ever be evaluated if you run that function. The problem is: the point of said statement is to run the function in the first place.
import sys
def hello(a, b):
print 'hello and that\'s your sum: {0}'.format(a + b)
if __name__ == '__main__':
hello(int(sys.argv[1]), int(sys.argv[2]))
Moreover see #thibauts answer about how to call python script.
There are more than a couple of mistakes in the code.
'import sys' line should be outside the functions as the function is itself being called using arguments fetched using sys functions.
If you want correct sum, you should cast the arguments (strings) into floats. Change the sum line to --> sum = float(a) + float(b).
Since you have not defined any default values for any of the function arguments, it is necessary to pass both arguments while calling the function --> hello(sys.argv[2], sys.argv[2])
import sys
def hello(a,b):
print ("hello and that's your sum:")
sum=float(a)+float(b)
print (sum)
if __name__ == "__main__":
hello(sys.argv[1], sys.argv[2])
Also, using "C:\Python27>hello 1 1" to run the code looks fine but you have to make sure that the file is in one of the directories that Python knows about (PATH env variable). So, please use the full path to validate the code.
Something like:
C:\Python34>python C:\Users\pranayk\Desktop\hello.py 1 1
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 want the user to enter the arguments using command line with variable names in the command line itself.
For example,
python test.py a=10 b=20
The code should be able to use a=10 and b=10 wherever needed.
I am able to achieve python test.py 10 20 but not the above given thing. I am wondering if that is even possible in python?
You cannot directly assign a variable from the command line, but sys.argv from the sys module will return a list of all your command line arguments. So you can pass the values, and then assign them in the first lines of your program like so.
import sys
# expect program to be run with "python test.py 10 20"
file_name = sys.argv[0] # this will be "test.py" in our example
a = sys.argv[1] # this will be 10
b = sys.argv[2] # this will be 20
Check out this article for more detailed information on this topic.
https://www.geeksforgeeks.org/how-to-use-sys-argv-in-python/
You can use sys and getopt to do this in a similar fashion to how you would check for command-line arguments in C. You can see if this is the right choice for your use-case by reading the documentation here.
You can do something like this (very hacky):
import sys
def assign_variable_dynamically(expression):
var_name, value = expression.split("=")
globals()[var_name] = value
# for the following run: python test.py a=10 b=20
# you will get:
assign_variable_dynamically(sys.argv[1])
assign_variable_dynamically(sys.argv[2])
print(a) # output: 10
print(b) # output: 20
My package has the following structure:
mypackage
|-__main__.py
|-__init__.py
|-model
|-__init__.py
|-modelfile.py
|-simulation
|-sim1.py
|-sim2.py
The content of the file __main__.py is
from mypackage.simulation import sim1
if __name__ == '__main__':
sim1
So that when I execute python -m mypackage, the script sim1.py runs.
Now I would like to add an argument to the command line, so that python -m mypackage sim1 runs sim1.py and python -m mypackage sim2 runs sim2.py.
I've tried the follwing:
import sys
from mypackage.simulation import sim1,sim2
if __name__ == '__main__':
for arg in sys.argv:
arg
But it runs boths scripts instead of the one passed in argument.
In sim1.py and sim2.py I have the following code
from mypackage.model import modelfile
print('modelfile.ModelClass.someattr')
You can simply call __import__ with the module name as parameter, e.g.:
new_module = __import__(arg)
in your loop.
So, for example, you have your main program named example.py:
import sys
if __name__ == '__main__':
for arg in sys.argv[1:]:
module=__import__(arg)
print(arg, module.foo(1))
Note that sys.argv[0] contains the program name.
You have your sim1.py:
print('sim1')
def foo(n):
return n+1
and your sim2.py:
print('sim2')
def foo(n):
return n+2
then you can call
python example.py sim1 sim2
output:
sim1
sim1 2
sim2
sim2 3
Suppose you have you files with following content.
sim1.py
def simulation1():
print("This is simulation 1")
simulation1()
main.py
import sim1
sim1.simulation1()
output
This is simulation 1
This is simulation 1
When you import sim1 into main.py and calls its function simulation1, then This is simulation 1 gets printed 2 times.
Because, simulation1 is called inside sim1.py and also in main.py.
If you want to run that function in sim1.py, but don't want to run when sim1 is imported, then you can place it inside if __name__ == "__main__":.
sim1.py
def simulation1():
print("This is simulation 1")
if __name__ == "__main__":
simulation1()
main.py
import sim1
sim1.simulation1()
output
This is simulation 1
Your code doesn't do what you want it to do. Just sim1 doesn't actually call the function; the syntax to do that is sim1().
You could make your Python script evaluate random strings from the command line as Python expressions, but that's really not a secure or elegant way to solve this. Instead, have the strings map to internal functions, which may or may not have the same name. For example,
if __name__ == '__main__':
import sys
for arg in sys.argv[1:]:
if arg == 'sim1':
sim1()
if arg == 'mustard':
sim2()
if arg == 'ketchup':
sim3(sausages=2, cucumber=user in cucumberlovers)
else:
raise ValueError('Anguish! Don\'t know how to handle %s' % arg)
As this should hopefully illustrate, the symbol you accept on the command line does not need to correspond to the name of the function you want to run. If you want that to be the case, you can simplify this to use a dictionary:
if __name__ == '__main__':
import sys
d = {fun.__name__: fun for fun in (sim1, sim2)}
for arg in sys.argv[1:]:
if arg in d:
d[arg]()
else:
raise ValueError('Anguish! etc')
What's perhaps important to note here is that you select exactly which Python symbols you want to give the user access to from the command line, and allow no others to leak through. That would be a security problem (think what would happen if someone passed in 'import shutil; shutil.rmtree("/")' as the argument to run). This is similar in spirit to the many, many reasons to avoid eval, which you will find are easy to google (and you probably should if this is unfamiliar to you).
If sim1 is a module name you want to import only when the user specifically requests it, that's not hard to do either; see importing a module when the module name is in a variable but then you can't import it earlier on in the script.
if __name__ == '__main__':
import sys
modules = ['sim1', 'sim2']
for arg in sys.argv[1:]:
if arg in modules:
globals()[arg] = __import__(arg)
else:
raise ValueError('Anguish! etc')
But generally speaking, modules should probably only define functions, and leave it to the caller to decide if and when to run them at some time after they import the module.
Perhaps tangentially look into third-party libraries like click which easily allow you to expose selected functions as "subcommands" of your Python script, vaguely similarly to how git has subcommands init, log, etc.
I'm trying to run different functions from a python script(some with arguments and some without)
So far I have
def math(x):
ans = 2*x
print(ans)
def function1():
print("hello")
if __name__ == '__main__':
globals()[sys.argv[1]]()
and in the command line if I type python scriptName.py math(2)
I get the error
File "scriptName.py", line 28, in <module>
globals()[sys.argv[1]]()
KeyError: 'mat(2)'
New to python and programming so any help would be apprecitated. This is also a general example...my real script will have a lot more functions.
Thank you
Try this!
import argparse
def math(x):
try:
print(int(x) * 2)
except ValueError:
print(x, "is not a number!")
def function1(name):
print("Hello!", name)
if __name__ == '__main__':
# if you type --help
parser = argparse.ArgumentParser(description='Run some functions')
# Add a command
parser.add_argument('--math', help='multiply the integer by 2')
parser.add_argument('--hello', help='say hello')
# Get our arguments from the user
args = parser.parse_args()
if args.math:
math(args.math)
if args.hello:
function1(args.hello)
You run it from your terminal like so:
python script.py --math 5 --hello ari
And you will get
>> 10
>> Hello! ari
You can use --help to describe your script and its options
python script.py --help
Will print out
Run some functions
optional arguments:
-h, --help show this help message and exit
--math MATH multiply the integer by 2
--hello HELLO say hello
Read More: https://docs.python.org/3/library/argparse.html
Here is another approach you can take:
#!/usr/bin/env python3
"""Safely run Python functions from command line.
"""
import argparse
import ast
import operator
def main():
# parse arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("function", help="Python function to run.")
parser.add_argument("args", nargs='*')
opt = parser.parse_args()
# try to get the function from the operator module
try:
func = getattr(operator, opt.function)
except AttributeError:
raise AttributeError(f"The function {opt.function} is not defined.")
# try to safely eval the arguments
try:
args = [ast.literal_eval(arg) for arg in opt.args]
except SyntaxError:
raise SyntaxError(f"The arguments to {opt.function}"
f"were not properly formatted.")
# run the function and pass in the args, print the output to stdout
print(func(*args))
if __name__ == "__main__":
main()
Then you can execute this by doing the following:
./main.py pow 2 2
4
We use the argparse module from Python's Standard Library to facilitate the parsing of arguments here. The usage for the script is below:
usage: main.py [-h] function [args [args ...]]
function is the name of the function you want to run. The way this is currently structured is to pull functions from the operator module, but this is just an example. You can easily create your own file containing functions and use that instead, or just pull them from globals().
Following function you can supply any number of arguments that you want. Those arguments will be ran through ast.literal_eval to safely parse the arguments and get the corresponding types.
The cool thing about this is your arguments are not strictly limited to strings and numbers. You can pass in any literal. Here is an example with a tuple:
./main.py getitem '(1, 2, 3)' 1
2
These arguments are then passed to the selected function, and the output is printed to stdout. Overall, this gives you a pretty flexibly framework in which you can easily expand the functionality. Plus, it avoids having to use eval which greatly reduces the risk of doing something of this nature.
Why not to use eval:
Here is a small example of why just using eval is so unsafe. If you were to simply use the following code to solve your issue:
def math(x):
ans = 2*x
print(ans)
def function1():
print("hello")
if __name__ == '__main__':
print(eval(sys.argv[1]])) # DO NOT DO IT THIS WAY
Someone could pass in an argument like so:
python main.py 'import shutil; shutil.rmtree("/directory_you_really_dont_want_to_delete/")'
Which would in effect, import the shutil module and then call the rmtree function to remove a directory you really do not want to delete. Obviously this is a trivial example, but I am sure you can see the potential here to do something really malicious. An even more malicious, yet easily accessible, example would be to import subprocess and use recursive calls to the script to fork-bomb the host, but I am not going to share that code here for obvious reasons. There is nothing stopping that user from downloading a malicious third party module and executing code from it here (a topical example would be jeilyfish which has since been removed from PyPi). eval does not ensure that the code is "safe" before running it, it just arbitrarily runs any syntactically correct Python code given to it.
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)