Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a specific Python function from a batch file?

Let's say I have this simple Python script, named MyScript.py:

def MyFunction(someInput):
    #Do something with input

I would like to write a batch file that specifically calls MyFunction from MyScript with someInput.

Now, I could do some Python-foo and add:

import sys

def MyFunction(someInput):
    #Do something with input

if __name__ == "__main__":
    eval(sys.argv[1])

Then I can use a batch like this:

python MyScript.py MyFunction('awesomeInput')
pause

But I have a feeling there's a more obvious solution here that doesn't involve me retrofitting "_name_ == "_main_" logic in each of my scripts.

like image 345
Derek Avatar asked Mar 10 '14 22:03

Derek


People also ask

How do I execute a function in PY file?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

What is %% g'in batch file?

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'.

How do you batch a process in python?

You can write a batch script in python using os. walk() to generate a list of the files and then process them one by one with your existing python programs. If there are other files in the directory you might want to add a regex to ensure you only process the files you're interested in.


1 Answers

If you are in the same folder as the script you can do:

python -c "import Myscript;Myscript.MyFunction('SomeInput')"
like image 152
Noelkd Avatar answered Sep 20 '22 07:09

Noelkd