1 minute read

March 2023

OverviewPermalink

A quick post to remind me how to call a Python script via PowerShell, passing in an argument and saving the output of the script to a variable in PowerShell using a couple of demo scripts that do nothing more than pass a string to the Python script and return it with text added.

Test machine specs:

Ubuntu 20.04.5 LTS
PSVersion 7.3.2
Python 3.10.5 

This should work as is with Python 3.6+ (uses f-string formatting).

I have a virtual environment created with the required Python packages installed. The Python script simply outputs the text I need via the print function and exits.

Here is the Python script that takes an argument and prints it out.

# Print out input text from command line argument and exit.
# Used as demo to get data from Python Script in PowerShell.
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("text")
args = parser.parse_args()
print(f"{args.text} From Python script.")
sys.exit()
view raw main.py hosted with ❤ by GitHub

The output can be saved to a variable in PowerShell by calling the script like so.

# Calls a Python script. The output of the print statement is saved in a Variable.
$pythonProgramPath = ".venv/bin/python" # location of the Python executable
$pythonScriptPath = "/python/powershell-call-python/main.py" # location of script file.
$arg = "hello"
$pythonOutput = & $pythonProgramPath $pythonScriptPath $arg
$pythonOutput

The PythonProgramPath can either point to the main install of Python (or just Python if it is added to the Path environment variable) or a virtual environment if extra packages are required / installed for the script to run.

I was using this method to work with JWTs. I was struggling to so with PowerShell and already had the Python scripts written so I only had to grab the output of the script to use the JWT values in my PowerShell script.