10

I wrote a script. When it starts, it won't stop, and it keeps getting data from the Internet. I can call it this way:

cd /User/Desktop/project/internetScanner/
python3 main.py start

But I would like to call it directly from the terminal like this, within the destination:

internetScanner start

How can I do so?

slhck
  • 235,242
Ted Wong
  • 943

3 Answers3

27

You should probably rename your file main.py to internetScanner. Extensions on *nix are purely optional. It shouldn't matter here.

mv main.py internetScanner

Then, add the following line to this file, right at the beginning:

#!/usr/bin/env python3

This will make sure that when the shell executes the file, it will know to use python3 to interpret the content. This is known as the Shebang. Now, make the file executable:

chmod +x internetScanner

You can now run your program from within /User/Desktop/project/internetScanner/:

./internetScanner start

Your program will run in the foreground and continue running until you press Ctrl-C. If you do not want this, you can also start the program in the background, by adding an ampersand after the command:

./internetScanner start &

This will let your program run, but you can continue to use your shell. This is called job control, and there's a simple tutorial about it here.

If you now want to be able to run the program from anywhere on the system, you need to add the internetScanner directory to your PATH: What are PATH and other environment variables, and how can I set or use them?

slhck
  • 235,242
2

Assuming no other files in /User/Desktop/project/internetScanner/ are needed, if you want to install for a single user, link (ln -s) main.py to $HOME/bin/internetScanner. You'll probably need to mkdir $HOME/bin first.

Next time you log in, $HOME/bin will probably be added to your PATH. If you want it available for all users, copy it to /usr/local/bin.

If it must execute in /User/Desktop/project/internetScanner/, either start by importing os and calling

os.chdir('/User/Desktop/project/internetScanner/') 

or create a launcher script in $HOME/bin or /usr/local/bin that changes to /User/Desktop/project/internetScanner/ and executes the script.

slhck
  • 235,242
Perkins
  • 181
0

Put alias internetScanner "python /User/Desktop/project/internetScanner/main.py" in .aliases file (for csh). For bash, put alias internetScanner="python /User/Desktop/project/internetScanner/main.py" in .bashrc. After that you can use internetScanner start from anywhere.

Excalibur
  • 1
  • 2