Python – Run Python functions from PowerShell

Run Python functions from PowerShell… here is a solution to the problem.

Run Python functions from PowerShell

I have a .py file with a script.

I want to run it from PowerShell. I can write like this:

C:\Users\AAA\AppData\Local\Continuum\Anaconda3\pythonw.exe "X:\Data\_Private\Data\test.py"

But I want to pass some parameters to the script. Therefore, I set all the scripts to the main(argument1, argument2) function. It looks like this :

def main(argument1, argument2):
    def Hello(argument1, argument2):
        print("Hi " + argument1 + " and " + argument2 + "!")

The rest of the script continues.

Maybe someone can tell me how to run that script from PowerShell in one line and pass parameters?

Solution

I think you are looking for something like this :

import sys

def Hello(argument1, argument2):
    print("Hi " + argument1 + " " + argument2 + "!")

if __name__ == "__main__":
    Hello(sys.argv[1],sys.argv[2])

From PowerShell:

python test.py 1 2

Of course, you may want to check if your argv index is in range.

Related Problems and Solutions