Home > Back-end >  Why do we first need the cd command when opening the .py file in the terminal by python?
Why do we first need the cd command when opening the .py file in the terminal by python?

Time:11-04

Why can't we open the .py file with its path by python?

noob asking. Apologies if I am stupid.

CodePudding user response:

You don't.

If you have the file /home/user/scripts/tests/main.py, with the following content:

print("Hello World")

Running python3 /home/user/scripts/tests/main.py will run the python script as expected.

There may be an issue with your PATH or with how you're entering the path to the file

CodePudding user response:

You probably use similar construction:

myscript.py

It means, that terminal consider your input as a command, and tries to find in in $PATH.

Firstly you need to use absolute or relative addressation:

./myscript.py
# or
/path/to/file/myscript.py

Secondly, you need to make sure, your script has an executable bit:

chmod  x myscript.py

Thirdly, make sure you use shebang in the first line of your scriptb:

#!/usr/bin/python

Shebang explains to your shell, which app should process the file. Otherwise you'll need to run it via python directly:

python myscript.py
  • Related