3

I'm using Zsh on MacOS Catalina.

I was reading Automate the Boring Stuff with Python and in it the author runs mapIt.py simply by typing mapit into the terminal.

In order to do this I added a shebang to the top of my code:

#!/usr/bin/env python

I also marked it with chmod +x script.py and added the directory to my PATH.

However in order to run it, I need to type script.py. Typing just script doesn't work.
How can I do this?

1 Answer 1

3

I think I found it online. This fragment

C:\> mapit 870 Valencia St, San Francisco, CA 94110

(namely C:\>) and other details indicate the author uses Windows. In Windows there are ways to run files of certain extensions by typing their names without extensions. The author most likely has enabled the feature for .py. Compare this: Making Python scripts run on Windows without specifying .py extension.

In Unix/Linux .py in script.py is just a part of the name. There is no concept of extension (other than the concept in user's mind maybe).

So just name the script script instead of script.py. If you want to be able to run the same script regardless if you type script.py or script, then place the script under one name and make a symlink from the other name to the actual script.

Note (at least in Linux) there is script(1) utility. Depending on your PATH a command script will run the script or the utility (if installed).


Another approach is to make your shell try to run foo.py if foo resulted in command not found (for any foo). See this general question:

and these two answers as examples (note they are for Bash):

In Zsh the function is named command_not_found_handler. Build your solution by porting one of the examples to Zsh.

2
  • Would the Python script still be able to execute if it didn't have the .py extension?
    – alibiineed
    Commented May 3, 2020 at 20:54
  • 1
    @alibiineed If the permissions and the shebang are right then it should. Why don't you just try? Commented May 3, 2020 at 20:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .