- Mastering Interoperability: How to Run PowerShell Commands in Python Efficiently
- 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
- Executing PowerShell from Python
- What you need
- The code
- Conclusion
Mastering Interoperability: How to Run PowerShell Commands in Python Efficiently
Picture this: you are an expert engineer working on a crucial automation project. You have been using Python for your code, but you suddenly come across a problem that requires the functionality of Powershell. How do you integrate these two seemingly disparate languages? The answer lies in knowing _how to run a Powershell command in Python_.
This comprehensive guide will take you through the five essential steps to achieve a seamless fusion between Python and Powershell. We’ll explore various techniques and dive into the reasoning behind each method. By the end of this article, you will be armed with the knowledge necessary to tackle any challenging situation where Python and Powershell need to coexist in harmony.
**Step 1: Understand the subprocess module in Python**
The first step in running a Powershell command in Python is to familiarize yourself with the _subprocess_ module. This module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. It provides a consistent interface for creating and interacting with additional processes in a robust and efficient manner.
It is important to note that the subprocess module supersedes the older modules such as os.system, os.spawn*, and commands. Therefore, it is highly recommended to use the subprocess module for new projects.
**Step 2: Explore PowerShell command execution options**
To call a Powershell command from Python, it is crucial to understand the different ways to execute Powershell cmdlets or scripts. Here are some examples:
– Using the `-Command` flag: When launching Powershell from the command line or another script, you can utilize the `-Command` flag to specify the command you wish to execute.
“`
powershell.exe -Command “Get-Process”
“`
– Using the `-File` flag: If you prefer to store your Powershell code in a script file, you can run it using the `-File` flag followed by the file path.
“`
powershell.exe -File “C:scriptsexample_script.ps1”
“`
– Implementing the `-ExecutionPolicy` flag: In some cases, you might encounter execution policy restrictions that prevent the execution of Powershell scripts. To work around this, include the `-ExecutionPolicy` flag with the `Bypass` value.
“`
powershell.exe -ExecutionPolicy Bypass -File “C:scriptsexample_script.ps1”
“`
**Step 3: Utilize the subprocess module to call Powershell commands**
Now that you are familiar with the subprocess module and the possible ways to execute Powershell commands, it’s time to put the two together. The following examples demonstrate various techniques for invoking Powershell commands from within a Python script using the subprocess module:
– **Example 1:** Running a simple cmdlet
result = subprocess.run([“powershell.exe”, “-Command”, “Get-Process”], capture_output=True, text=True)
print(result.stdout)
“`
– **Example 2:** Executing a Powershell script file
result = subprocess.run([“powershell.exe”, “-File”, “C:\scripts\example_script.ps1”], capture_output=True, text=True)
print(result.stdout)
“`
– **Example 3:** Bypassing the execution policy
result = subprocess.run([“powershell.exe”, “-ExecutionPolicy”, “Bypass”, “-File”, “C:\scripts\example_script.ps1”], capture_output=True, text=True)
print(result.stdout)
“`
**Step 4: Error checking and return codes**
In the previous step, we were able to execute Powershell commands from within our Python code. However, it is of utmost importance to also handle errors and check return codes to ensure the success of the execution.
The _subprocess.run()_ function returns an object with a `returncode` attribute containing the return code of the executed command. A return code of zero typically indicates successful execution, while non-zero values signify an error.
Consider adding error checking to your Python script by examining the `returncode` attribute as shown in the example below:
result = subprocess.run([“powershell.exe”, “-Command”, “Get-Process”], capture_output=True, text=True)
if result.returncode == 0:
print(“Powershell command executed successfully.”)
print(result.stdout)
else:
print(“An error occurred during Powershell command execution.”)
print(result.stderr)
“`
**Step 5: Using PEP 8 guidelines for clear and concise code**
As a final tip, always adhere to _PEP 8_ guidelines when writing Python code. This best practice ensures that your code remains clean, cohesive, and easily readable by other engineers. Following these guidelines will not only make your code more maintainable but also minimize technical debt within your team or organization.
By following these five key steps, you have unlocked the potential to run Powershell commands in your Python scripts effortlessly. The seamless integration of Python and Powershell will undoubtedly open up new opportunities for development and automation in your projects. Happy coding!
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)
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.
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.
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, 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.
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, 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.
Executing PowerShell from Python
I have an experiment that I am working on and thought that leveraging Python would be fun. As part of that experiment, I would need to execute PowerShell from Python since only PowerShell cmdlets are available to do what I need. After a little research a week of letting it simmer, I was able to sit down the last night and work it out. Part of it is my unfamiliarity with Python for what I am doing, and the other part is just me not thinking about the problem holistically.
What you need
You will need PowerShell installed on your system and Python 3.6+. This would work cross-platform. I did my testing on Kubuntu 20.10 running PowerShell as a snap package. You will not need any external libraries since we use one of the many great libraries that ship out of the box with Python.
The code
All we need is to create a file call ps.py, and then we can import the subprocess module.
Now we can make our run method that we will use to execute our PowerShell command.
def run(self, cmd): completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True) return completed
Let’s make our Python file executable and then create the commands we want to execute. One command has the correct syntax, and one command has bad syntax. This will demonstrate how to use the return of the subprocess.run method.
if __name__ == '__main__': hello_command = "Write-Host 'Hello Wolrd!'" hello_info = run(hello_command) if hello_info.returncode != 0: print("An error occured: %s", hello_info.stderr) else: print("Hello command executed successfully!") print("-------------------------") bad_syntax_command = "Write-Hst 'Incorrect syntax command!'" bad_syntax_info = run(bad_syntax_command) if bad_syntax_info.returncode != 0: print("An error occured: %s", bad_syntax_info.stderr) else: print("Bad syntax command executed successfully!")
Here is the complete file.
import subprocess def run(self, cmd): completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True) return completed if __name__ == '__main__': hello_command = "Write-Host 'Hello Wolrd!'" hello_info = run(hello_command) if hello_info.returncode != 0: print("An error occured: %s", hello_info.stderr) else: print("Hello command executed successfully!") print("-------------------------") bad_syntax_command = "Write-Hst 'Incorrect syntax command!'" bad_syntax_info = run(bad_syntax_command) if bad_syntax_info.returncode != 0: print("An error occured: %s", bad_syntax_info.stderr) else: print("Bad syntax command executed successfully!")
Execute ps.py, and we can see the output. The first command didn’t fail and returned an exit code of zero, and we print that it ran successfully. The second command has a typo, and we get an exit code of one that we then print the error that came from standard error.
$ python ps.py Hello command executed successfully! ------------------------- An error occurred: %s b"\x1b[91mWrite-Hst: \x1b[91mThe term 'Write-Hst' is not recognized as the name of a cmdlet, function, script file, or operable program.\nCheck the spelling of the name, or if a path was included, verify that the path is correct and try again.\x1b[0m\n"
Conclusion
That’s it, now you can feel free to build up any kind of command that you want to be executed, even multiline commands, and it should work.
If you enjoy the content then consider buying me a coffee.
Copyright © 2014-2023 by Jamie Phillips. The opinions expressed herein are my own and do not represent those of my employer or any other third-party views in any way. This work is licensed under a Creative Commons Attribution 4.0 International License.