Run Python Script in Windows PowerShell

  1. Run Python in PowerShell Using py Command
  2. Run Python in PowerShell Using ./<filename>.py

In this tutorial, we will look into the multiple methods to run the Python script or .py files in Windows PowerShell. The requirement to run a Python script on a machine is to have Python installed in it. We can check the installed version of Python 2 or Python 3 in Windows PowerShell with the following commands.

Python 2:

py -2 --version

Python 3:

py -3 --version

If the required version of Python is not installed, it can be downloaded and installed from this link. Once we have the required version of Python, we can run the Python script in Windows PowerShell in the following ways.

Run Python in PowerShell Using py Command

We can run the Python script in PowerShell using the py command. To run the script using py command, we will need to mention the version of Python required to run the script and the name of the script file.

The example command below demonstrates how to run the Python script test.py in Windows PowerShell using py command.

For Python 2:

py -2 test.py

For Python 3:

py -3 test.py

Run Python in PowerShell Using ./<filename>.py

We can also execute the Python script through Windows PowerShell using the ./ before the script name. It will open a new window and will show the output of the script and close. The problem that can occur in this method is that the user will not be able to see the output of the script, as the output window will close after the execution of the script.

The solution to this problem is to use the input() method at the end of the script. As the input() method waits for the user to enter the input value. Therefore the output window will not close and will remain open until the user does not press the Enter key.

We can use the following command to run the Python script test.py through Windows PowerShell.

./test.py
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.