Unable to run .sh and .ps1 file with Python

Question:

I learned that you can write scripts and run multiple commands by executing a .sh or .ps1 file in Bash and PowerShell respectively. However, when I run my files I get the same error (both in Bash and PowerShell) and I am unable to understand why.

Python version I’m running is 3.11.4
OS: Win11

Script I’m trying to run is:

python3 -c "print(1)"

Command I’m executing
In PowerShell:

./test.ps1

In Bash:

./test.sh

Error message I receive is:

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

When I run it with python, for example:

py test.ps1

Or

py test.sh

I receive the following error:

  File "D:pythontestingtest.ps1", line 1
    python3 -c "print(1)"
               ^^^^^^^^^^
SyntaxError: invalid syntax

The fact that it shows the contents of the file it means it is running it, but I’m unable to figure out what’s the problem with the syntax.

Asked By: Vasee Aleem

||

Answers:

You’re running the command in a Python REPL. This is evident by the error you get – it’s treating the command you wrote as Python code, which is not valid syntax. You need to run that command in a shell. Open your regular, plain-old terminal and run the command in there.

Answered By: bgfvdu3w
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.