How to Run a PowerShell Script From Within the Python Program
-
Python
subprocess.Popen()
Method -
Run a PowerShell Script From Within the Python Program Using the
Popen()
Method
Windows PowerShell consists of tens of in-built cmdlets, which provide a rich set of features. Some of these features are unique and only available via PowerShell; hence, it is very useful if we can use PowerShell scripts within other programming languages like Python.
This article will focus on executing PowerShell logic from Python code.
Python subprocess.Popen()
Method
In Python, the external programs can be executed using the subprocess.Popen()
method. The subprocess
module consists of several more efficient methods than the ones available in the old os
module; hence, it is recommended to use the subprocess
module instead of the os
module.
Since we will run a PowerShell code from the Python program, the most convenient approach is to use the Popen
class in the subprocess
module. It creates a separate child process to execute an external program.
The one thing to keep in mind is that this process is platform-dependent.
Whenever you call subprocess.Popen()
, the Popen
constructor is called. It accepts multiple parameters, as shown in the following.
subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
The argument args
is used to pass the command that starts the external program. There are two ways that you can pass the command with its parameters.
-
As a Sequence of Arguments
Popen(["path_to_external_program_executable", "command_args1", "command_args2", ...])
-
As a Single Command String
Popen('path_to_external_program_executable -command_param1 arg1 -command_param2 arg2 ...')
The sequence of arguments is recommended with the Popen
constructor.
The next important argument is the stdout
parameter which we will be used in the next section. This specifies the standard output that the process should use.
Run a PowerShell Script From Within the Python Program Using the Popen()
Method
First, create a simple PowerShell script that prints to the console window.
Write-Host 'Hello, World!'
We will be saving it as sayhello.ps1
.
Next, we will be creating a Python script, runpsinshell.py
. Since we will use the subprocess.Popen()
command, we must import the subprocess
module first.
import subprocess
Then we will call the Popen
constructor with the args
and stdout
parameters, as shown in the following.
p = subprocess.Popen(["powershell.exe", "D:\\codes\\sayhello.ps1"], stdout=sys.stdout)
As you can see, the arguments have been passed as a sequence which is the recommended way. The first argument is the external program executable name, and the next is the file path to the previously created PowerShell script.
Another important thing to remember is that we should specify the standard output parameter as sys.stdout
. To use the sys.stdout
in your Python program, we must also import the sys
module.
The final program should look as follows.
import subprocess
import sys
p = subprocess.Popen(["powershell.exe", "D:\\codes\\sayhello.ps1"], stdout=sys.stdout)
p.communicate()
Finally, let’s run the Python program, as shown in the following.
python .\runpsinshell.py
Output:
As expected, the PowerShell script has been executed from the Python code and printed the Hello, World!
string to the PowerShell window.
The Python program can also be written by passing the Popen
constructor arguments as a single string.
import subprocess
import sys
p = subprocess.Popen(
'powershell.exe -ExecutionPolicy RemoteSigned -file "D:\\codes\\sayhello.ps1"',
stdout=sys.stdout,
)
p.communicate()
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.