Aertonas
Aertonas

Reputation: 69

Running Python Function from PowerShell

I have a .py file with a script.

I want to run it from the PowerShell. I can do it by writing:

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

However I want to pass some arguments to the script. Thus, I set all script as a main(argument1, argument2) function. It looks like this:

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

And the rest of the script continues.

Maybe someone could tell me how can I run that script from PowerShell in one line and passing arguments?

Upvotes: 5

Views: 4719

Answers (2)

Boendal
Boendal

Reputation: 2526

The use of the main funciton should looks like this:

import sys

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

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

You only define the function main but you never call it.

Read for example here more about main: main
Read more about sys.argv: sys_argv

Upvotes: 1

Jibbity jobby
Jibbity jobby

Reputation: 1325

I think something like this is what you are looking for:

import sys

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

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

And from PowerShell:

python test.py 1 2

Of course you probably want to check your argv indices are within range.

Upvotes: 3

Related Questions