0

I want to run a python script foo.py from the command line like this

$ foo

Using a shebang in foo.py, for example:

#!/usr/bin/env python
print('this is foo')

allows me to call it like this:

$ ./foo.py

How do I drop the leading ./ and the trailing .py?

AS_Butler
  • 281
  • 2
  • 12
  • 3
    The leading `./` is there for security reasons. And you can just rename the file. – Klaus D. Aug 29 '20 at 05:03
  • 1
    This might help: `PATH="$PATH:$PWD"` – Cyrus Aug 29 '20 at 05:03
  • 5
    @Cyrus Don't give that line without explaining the security implications! – Klaus D. Aug 29 '20 at 05:05
  • 2
    To explain: if you include the current working directory in your `PATH` someone can put a script name like a standard command (for example `ls`) in some folder. When you enter that folder and run `ls` the script will be executed with your rights. – Klaus D. Aug 29 '20 at 05:09
  • @KlausD. `bash` would only execute `ls` in `$PWD` if it did not find `ls` in one of the directories mentioned in `$PATH` before. I had not written `PATH="$PWD:$PATH"`. – Cyrus Aug 29 '20 at 05:18
  • Ah - I see. So an alternative would be to put `foo.py` in something that is on my PATH already? – AS_Butler Aug 29 '20 at 05:31
  • 1
    Does this answer your question? [How do I run a shell script without using "sh" or "bash" commands?](https://stackoverflow.com/questions/8779951/how-do-i-run-a-shell-script-without-using-sh-or-bash-commands) I know it says "shell script", but it's the same process for any script. – wjandrea Aug 29 '20 at 05:44
  • 1
    Yes, move `foo.py` as `foo` to a directory that is in your PATH. – Cyrus Aug 29 '20 at 06:19

1 Answers1

1

First, rename the file from foo.py to foo.

Then, move the file to /usr/local/bin/ or /home/user/.local/bin if the script will only be executed by a single user. Instead, if your script is placed somewhere in the system for example "/path/to/foo", you could add your "/path/to/foo" to the $PATH variable.

After opening a new terminal session. You should be able to execute the script without the "./" and ".py".

By the way "./" means that you want to execute a file in the current working directory. It is always possible to execute a file using a full path of the file, for example "/usr/bin/something_to_run".

Please consider reading about PATH variable here.

mri1939
  • 196
  • 5