The PowerShell -replace operator is an excellent function for substituting characters or sequences of characters in a string. The essential advantage of the operator is that it accepts the substitution of a substring with literal strings, wildcards, and regular expressions.
Continue readingAuthor Archives: Kiprono Koech
Process Finished With Exit Code 0 in Python
Python interpreter generates exit codes at the end of the execution to indicate if the code was executed successfully with no errors/exceptions.
The exit code 0 is the standard code used to indicate that our program is executed successfully with no errors. Any non-zero exit code is used for executions that terminated with errors or exceptions.
How to Read Python Exit Codes
Method 1: In some cases, exit codes are printed on the output console
Some IDEs and code editors, such as PyCharm and Sublime Text, print the exit code on the terminal once execution is done. For example,
1 2 3 |
# Code that executes with no errors result = (3*7.2)/0.7 print(result) |
When the above code is executed on Pycharm, the following content is printed on the console.

Next, let’s execute code that leads to an error in Pycharm.
1 2 3 |
# We cannot divide a number with zero result = (3*7.2)/0 print(result) |

Since the above code yielded a ZeroDivisionError, the execution was terminated with exit code 1.
Method 2: Running Python script on the terminal, then check the returned code
This is done by executing our script on the command line and then checking the value returned by the Python interpreter after the execution.
Example
First, save the following code in a script called exit_code1.py.
1 2 3 4 |
# Get the mean of three numbers and round off results to two decimal places mean = round(sum([56, 78, 83])/3, 2) name = "Eric" print(f"Hello, {name}, your mean mark is {mean}") |
Then you can execute it in the terminal with the following command
1 |
python3 exit_code1.py |
Lastly, check the code by running (for Unix users)
1 |
echo $? |
Or use the following command (Windows Users):
1 |
echo %errorlevel% |
The sequence “$?” for UNIX systems and “%errorlevel%” for Windows contains the exit code of the last command.
And, if we run code with errors, we get a non-zero exit code, as shown in this example (the code is saved on the exit_codetf.py file).
1 2 |
name = "Allan Smith" printt(name) |

Terminating Python Execution using Custom Exit Codes
The standard exit codes for Python are 0 and 1 – 0 for successful execution and 1 for abnormal termination. However, you can define a different exit code using the sys.exit(code) function.
Note: sys.exit() function accepts 8-bit exit codes, that is, any value between 0 and 255. If you provide a value outside that range, it’s treated as the modulo 256 of the given number.
For example, if you issue -4, sys.exit() will use 252 as the exit code, and if you supply 447, 191 will be used, as shown below.
1 2 3 4 |
# % is the modulo operator. print(-4 % 256) print(447 % 256) print(135 % 256) # When we use a value within the range modulo operator doesn't take effect. |
Output:
252 191 135
Let’s see how to supply a custom exit code using sys.exit(). In this example, we take an examination score and check if it is negative, between 0 and 100, or above 100. If the supplied mark is less than 0, we issue an exit code of 13, and if the score given is greater than 100, we exit with the code 101.
1 2 3 4 5 6 7 8 9 10 |
import sys mark = int(input("Enter the score: ")) if mark < 0: print("Oops! You entered a negative mark!") sys.exit(13) elif mark > 100: print("Oops! You entered a value greater than 100!") sys.exit(101) else: print(f"You entered {mark}") |
Output (first take with a negative mark):
Enter the score: -33 Oops! You entered a negative mark! Process finished with exit code 13
Output (second take with a score between 0 and 100):
Enter the score: 68 You entered 68 Process finished with exit code 0 Output (third take with a score above 100): Enter the score: 206 Oops! You entered a value greater than 100! Process finished with exit code 101
Conclusion
There are two standard exit codes in Python – 0 and 1. The former means the program exited normally – without errors, but the latter means the program terminated with errors.
This article discussed how to check the exit code and set custom codes in Python. After going through the guide, you should easily interpret exit codes in Python.
Optional Parameters in Powershell
Parameters in PowerShell can be passed into a function or a script using the param() block.
Continue readingWrite Output to Log Files in PowerShell Script
PowerShell provides different methods of writing output from a script/command into a log file. These log files come in handy when for troubleshooting and auditing PowerShell code.
Continue readingSet HTTP proxy with Python Requests
This article discusses how to pass proxies to the Python requests library. Before doing that, let” s discuss why we need proxies.
Continue readingRun Selenium Headless in Firefox and Chrome using Python
Selenium is one of the most powerful tools for web automation testing. Python can run this tool using the Selenium module, which can be installed from the PyPI.
Continue readingRunning Powershell Script Within Python Script
You can run a PowerShell script in Python using the subprocess or os module. In this article, we will learn how to execute a PowerShell script from Python in Windows, Mac, or Linux. The fundamental prerequisite is to have PowerShell installed on your system.
Windows comes preinstalled with PowerShell (you can update it by downloading the latest version from this link). You can install PowerShell core on Linux and Mac using the information below.
Installing PowerShell core in Linux
You can install PowerShell core on Debian by running the following commands from the terminal (source: Microsoft website). If you are running a different distribution, you can get the installation commands from here.
1 2 3 4 5 6 7 8 |
# Install system components sudo apt update && sudo apt install -y curl gnupg apt-transport-https # Import the public repository GPG keys curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - # Register the Microsoft Product feed sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-bullseye-prod bullseye main" > /etc/apt/sources.list.d/microsoft.list' # Install PowerShell sudo apt update && sudo apt install -y powershell |
Installing PowerShell Core on Mac
You can install PowerShell using Homebrew by running the following command on the terminal.
1 |
brew install --cask powershell |
Or update it using the commands
1 2 |
brew update brew upgrade powershell --cask |
Once done with the installation, you can start PowerShell from Windows, Linux, or Mac terminal by running this command in the terminal
1 |
pwsh |
And execute a PowerShell script using the command
1 |
pwsh <path/to/the/script> |
At this point, we are ready to execute a PowerShell script from within a Python script.
Running PowerShell Script Within Python Script
As an example, we will execute the PowerShell script named script1.ps1 with the content below. The script accepts one parameter, $Name, and prints a greeting message to the console based on the time of the day.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
param( $Name ) $noon = Get-Date -Hour 12 -Minute 0 -Second 0 $current_time = Get-Date Write-Host "The time is $current_time" if ($current_time -gt $noon){ Write-Host "Good afternoon, $Name`!" } else { Wite-Host "Good morning, $Name`!" } Then we can execute <em>script1.ps1</em> from Python code using the code below.<br><br>import subprocess, sys # Running "script1.ps1" script with the -Name parameter set to "Decker". p = subprocess.Popen(["pwsh", "script1.ps1", "-Name", "Decker"], stdout=sys.stdout) # Run this to send the result to stdout. Finish the execution process, in short. p.communicate() |
Output:
The time is 04/14/2023 18:46:50 Good afternoon, Decker!
If you want to save the output of the PowerShell script to a variable, you can send the output to the subprocess.PIPE, as shown below.
1 2 3 4 5 6 7 8 |
import subprocess, sys out = subprocess.Popen(["pwsh", "script1.ps1", "-Name", "Decker"], stdout=subprocess.PIPE) # read the content of the standard output (stdout) and decode it # to a string and save the results into "output" variable output = out.stdout.read().decode("utf-8") print(output) |
Output:
The time is 04/15/2023 17:37:35 Good afternoon, Decker!
You can also run the PowerShell script using the os module as follows.
1 2 3 4 |
import os return_code = os.system("pwsh script1.ps1 -Name Decker") print(return_code) |
If the execution runs successfully with no error, return_code=0. Note that os. system() has limited functionalities. The subprocess module discussed above provides more facilities for spawning new processes.
Conclusion
This guide discussed using the subprocess module to run the PowerShell script using Python across different platforms – Windows, Linux, and Mac.
Run PowerShell Script on Windows Startup
Running PowerShell scripts on Windows startup can automate essential tasks and save time.
Continue readingPowerShell String Contains Operator
PowerShell is a powerful tool for automation and administration tasks in Windows operating systems. It comes with a lot of built-in features and commands.
Continue readingCreate a File Name With the Current Date and Time in Python
You can create a file name with the current date and time in Python using the datetime module by following these steps.
Continue reading