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?
Thanks a lot for your feedback in advance and sorry for the very basic question.
CodePudding user response:
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.
CodePudding user response:
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.