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?

8
  • 3
    The leading ./ is there for security reasons. And you can just rename the file. Commented Aug 29, 2020 at 5:03
  • 1
    This might help: PATH="$PATH:$PWD" Commented Aug 29, 2020 at 5:03
  • 5
    @Cyrus Don't give that line without explaining the security implications! Commented Aug 29, 2020 at 5: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. Commented Aug 29, 2020 at 5:09
  • 1
    Does this answer your question? 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. Commented Aug 29, 2020 at 5:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.