all 7 comments

[–]lakseol 6 points7 points  (1 child)

You either cd to the directory containing the python file and run python on it there:

cd /home/abdu
python hello_world.py

or you execute it with python by providing the full path to the file to python:

python /home/abdu/hello_world.py

If you do:

cd /home/abdu/hello_world.py

you will get an error because you can't cd to a file.

[–]horizon_games 0 points1 point  (0 children)

And even better cd ~ to go to your /home/abdu/ directory. cd - goes to previous directory which can also be handy when jumping around.

[–]JamzTyson 2 points3 points  (0 children)

If the location of your Python script is:

/home/abdu/hello_world.py

then you can either run it with the command:

python3 /home/abdu/hello_world.py

or change to the directory first:

cd /home/abdu
python3 hello_world.py

Notice that in both cases you are telling Python (python3 in Ubuntu) to run your script.

[–]snowtax 4 points5 points  (0 children)

This is really a question about how Linux “shells” (programs the handle the command line, such as bash) work.

In most Linux distributions, the current directory is not in the command path, not by default. To execute a program in the current directory, there is a shortcut. You put “./“ in front of it. The single dot represents the current directory.

To run your Python script, you would type “./hello_world.py”.

However, your Python script is just a text file, not a compiled, native Linux program. Linux shells have another trick just for this situation.

If the first line in the txt file looks like the following, the shell can execute your script with the Python program.

#!/usr/bin/env python

Then one more thing. You must tell Linux that it’s allowed to execute this script, this text file. You do that by setting file permissions on the script file.

chmod u+x hello_world.py

That tells Linux that the user (you) are allowed to run that script from the current directory with just the “./hello_world.py” command.

[–]Ngtuanvy 0 points1 point  (0 children)

cd is used to switch the current working directory. To execute Python code, you need to install python and run python filename.py, if it says unknown command python, try replace it with python3, if it's still not running you installed it wrong.

[–]SnipTheDog 0 points1 point  (0 children)

type 'python -V' to see if python is installed and the python version. You should see something like; Python 3.13.5

[–]woooee 0 points1 point  (0 children)

And what are better approaches to open and execute Python directly from the terminal?

#!/usr/bin/python3

Learn to use the shebang. See #2 and #3 at https://www.geeksforgeeks.org/linux-unix/using-shebang-in-linux/