Run Python script via CMD - python

I have the following file: up.py
in this file:
def main(a_param, b_param, c_param):
// Code
if __name__ == '__main__':
exit(main())
I want to run this python file via the CMD, so I write this line:
python up.py False True False
But I get the next error:
TypeError: main() takes exactly 3 arguments (0 given)

This has nothing to do with CMD. Your main function expects three arguments, but you aren't passing any; you call it directly from your if __name__ == '__main__' block with just main().
Either get the arguments (eg from sys.argv) within that block and pass them to main, or remove the arguments from the function signature and get them within main.

You are trying to call your main function without arguments event though it requires 3 (a_param, b_param and c_param).
The command line parameters are stored in sys.argv. To call the main function with the first 3 command line parameters, you could this:
import sys
if __name__ == '__main__':
main(*sys.argv[1:4])
To clarify, * unpacks the argument list so main(*sys.argv[1:4]) is equivalent to main(sys.argv[1], sys.argv[2], sys.argv[3])

This code works for me
def main(a_param, b_param, c_param):
# Code
if __name__ == '__main__':
exit(main())
then:
$ python up.py False True False

Related

Running python main with arguments programmatically

Hello I am having a piece of code that is like this root/main.py
def main():
parser = argparse.ArgumentParser(prog="my prog")
parser.add_argument('--param-1')
parser.add_argument('--param-2')
parser_result, unknown = parser.parse_known_args()
...(do stuff with params)
if __name__ == '__main__':
main()
and root/folder1/folder2/util.py
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../../../")
import main
...
main.main(param1, param2) //errors here for wrong arguments
My question is how do I trigger my main with params, there is a way to use java like reflection to trigger and read correct in main my arguments? (Ideally I need as less changes on main as possible)
Also used and worked:
os.system("python /root/main.py --param-1 '{param1}' --param-2'{param2}'")
But I prefer a solution that keeps the same context and is cleaner.
There is probably a way to do it like that, but the simplest way would be to add default parameters to main:
main.py
def main(param1="anything", param2="anything"):
# do something with parameters
if __name__ == "__main__":
main()
util.py
import main
main.main(param1, param2)

Click: NameError: name not defined

I'm trying to use click to pass command-line arguments to a function but having difficulty. I'm trying to pass two command-line arguments with this:
python script.py --first-a hi --second-a there
Here's my attempt:
import click
#click.command()
#click.option("--first-a")
#click.option("--second-a")
def main(first_a, second_a):
print first_a, second_a
if __name__ == "__main__":
main(first_a, first_a)
This fails with:
NameError: name 'first_a' is not defined
I thought this had to do with dashes vs. underscores but removing the dashes and underscores (just using firsta and seconda) also fails with the same issue.
What am I doing incorrectly?
You need to call main() either without any arguments, or with a list of parameters as would normally be found in sys.argv.
Code:
if __name__ == "__main__":
main()
Test Code:
import click
#click.command()
#click.option("--first-a")
#click.option("--second-a")
def main(first_a, second_a):
print(first_a, second_a)
if __name__ == "__main__":
# test code
import sys
sys.argv[1:] = ['--first-a', 'hi', '--second-a', 'there']
# actual call to click command
main()
Results:
hi there

command line arguments PYTHON

Code
import sys
def main()
print(sys.argv)
Version - 3.3
File name Pytest.py
running the file with syntax pytest.py aaa bbb ccc
But it didn't print anything and not giving any error also
You never call main().
Python has no special main function that is run automatically, so instead, you can place the code that you want to run when the file is called from the command line into a special if block:
import sys
def main():
print(sys.argv)
if __name__ == '__main__':
main()
To elaborate #Blender's answer: Python functions does not compile like in C. Functions are statements - they are being executed when the control encounters them, and it begins at the first line of the file.
The following code is perfectly legal:
# get b somehow
if b:
def foo(): return 1
else:
def foo(): return 2
print(foo())

How does one call a function in a Python program from command line

For example let's say I have a file called myscript.py
This file contains the following code.
foo(var):
return var
How would I call the function foo with argument var on command line.
I know that I can go to the directory myscript.py is placed in and type.
>>> python myscript.py
Which will run myscript.py. The only problem is myscript.py doesn't automatically call foo when it is run.
I have tried using
if __name__ == "__main__":
foo( )
Which does not work for me. For some reason when I do that nothing happens. I get no error message and nothing is called.
You don't get any output because you don't generate any. Try calling print:
def foo(var):
print(var)
if __name__ == '__main__':
foo('Hello, world')
You have to use the sys module to pass arguments from the command line.
You can do this:
import sys
def foo(var):
return var
if __name__ == '__main__':
# arguments check
if len(sys.argv) != 2:
print "USAGE: %s <value>" % sys.argv[0]
sys.exit(1)
# get the agument so as to use it to the function call
arg = sys.argv[1]
# call the function using this argument
val = foo(arg)
# print the returned value
print val
Then you can run your python script by this command:
python myscript.py 3
giving as argument e.g. the number 3

How to call main() of a python script with arguments from mod_python.publisher?

I use a mod_python publisher function which calls the main() function of another python script with a custom built argv list. When I execute the publisher script from shell command line it works. But when I tried it through apache2 with mod_python, I get the error (shown below) that main takes no arguments.
File "/var/www/wabaServ/waba.py", line 15, in index
aba.main([ "aba.py","-i", "-b"])
TypeError: main() takes no arguments (1 given)
main() in aba.py is defined as:
def main(argv=None):
--code--
Note: if the list argument is not passed, aba.main() gets executed from mod_python.
The mod_python publisher function looks like:
import sys
sys.path.append("/u/scripts")
import aba
from cStringIO import StringIO
def index():
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
aba.main([ "aba.py","-i", "-b"])
sys.stdout = old_stdout
return(mystdout.getvalue())
The first logging statement says:
aba.main([ "aba.py","-i", "-b"])
And you say main is defined as:
def main(argv=None):
Therefore aba is passed in as the first argument into main() which takes up the argv argument and then there's no arguments left to pass that list in.
I don't think this has anything to do with mod_python.

Categories