2

Given I have a super simple Python file like:

print ("Hello World")

how can I make so when I open up my terminal and enter helloworld it will just execute that code and print "Hello World" to the terminal? Just in the same way some Python packages like "pip" work?

EDIT: I'm on a Mac but I'd like it to work on Linux and PC as well

Thanks a lot for your feedback in advance and sorry for the very basic question.

Difio
  • 145
  • 8
  • 4
    What operating system are you using? This is a feature of the OS, not of Python itself. – Blckknght Jan 04 '22 at 00:43
  • 1
    What OS are you using? You can make an alias that simply runs your python script, but how depends on the OS. – Gino Mempin Jan 04 '22 at 00:43
  • Thanks so much for all your feedback! I'm on a Mac but I'd ideally like it to work on Linux and PC as well! – Difio Jan 04 '22 at 09:42

2 Answers2

5

It depends on your operating system. On Linux or MacOS, you would (1) rename the file "helloworld", (2) add a shebang line to the beginning:

#! /usr/bin/env python3

(3) make it executable with chmod +x helloworld, and (4) move it into a directory on your path, like ~/bin.

If you are an Windows, you can leave the name as helloworld.py, but you need to move it into a directory that's on your path. For me, I have a directory called c:\bin where I put my tools.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

If you are on Linux, you can also set up an alias:

~$ helloworld
The command 'helloworld' was not found.
~$ alias helloworld="python -c 'print(\"hello world\")'"
~$ helloworld
hello world
~$

If you don't want to type the alias command in the terminal every time you open it, you can also add it at the end of your .bashrc file in the home directory (you might need to enable "Show hidden files" in the preferences of your file browser to see that file).

On Windows this can be set up in a similar way; see https://stackoverflow.com/a/21040825/14909980 for a detailed explanation.

TheEagle
  • 5,808
  • 3
  • 11
  • 39