0

I want to call a Python script from Powershell. I collect the arguments inside the variable arg, depending on if certain environment variables are set.
In the end, arg consists of this String: "--arg1 --arg3 arg3_value"
The problem is, that when I call the script with $arg, the arguments are not recognized inside the script:

>python .\some_script.py $arg
usage: some_script.py [-h] [--arg1] [--arg2] [--arg3 ARG3]
some_script.py: error: unrecognized arguments: --arg1 --arg3 arg3_value

If I write the arguments as a String in Powershell, it works:

> python  .\some_script.py --arg1 --arg3 arg3_value
arg1: True
arg3: arg3_value

Here is the code of the Python script:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--arg1', action="store_true", default=False)
parser.add_argument('--arg2', action="store_true", default=False)
parser.add_argument('--arg3')
args = parser.parse_args()

if args.arg1:
    print(f"arg1: {args.arg1}")

if args.arg2:
    print(f"arg2: {args.arg2}")

if args.arg3:
    print(f"arg3: {args.arg3}")

Does anyone have an idea, how to format the call correctly, so that the arguments are recognized?

Wuschelkopf24
  • 35
  • 1
  • 5
  • it sounds like you could `$arg= -split "--arg1 --arg3 arg3_value"` then `python .\some_script.py $arg` should work – Santiago Squarzon Apr 26 '23 at 13:39
  • 1
    just tried from my side, splitting `$arg` works fine so you could construct your string however you want and split it latter before passing the arguments to your py script – Santiago Squarzon Apr 26 '23 at 14:10
  • In short: In order to programmatically pass arguments to external programs, construct an _array_, with each parameter (option) name and parameter value / positional argument (operand) becoming its own element. E.g., to execute `foo -o "bar baz"`, use `$a = '-o', 'bar baz'; foo $a`. Note: You can _not_ use a _single string_ to encode _multiple_ arguments. See the linked duplicate for details. – mklement0 Apr 26 '23 at 15:48

0 Answers0