How can I enable syntax highlighting in a Python file without an extension?

You can select a specific syntax highlighting using the --syntax option, for example

nano --syntax=python myscript

Nano's default Python definition looks for one of two things an extension or a header match, as defined in /usr/share/nano/python.nanorc:

syntax "python" "\.py$"
header "^#!.*/python[-0-9._]*"

So this would match #!/bin/python. Unless you're writing something for the system, hard-coding the Python executable is a fairly bad idea... That's why env python is used these days.

The most simple way to fix Nano is to edit the definition by running sudoedit /usr/share/nano/python.nanorc and changing the header line to:

header "^#!.*python.*"

That is a lot more open.


There's actually a massively improved set of Syntax files available at the nanorc project on Github, that as well as improving other things, specifies:

header "^#!.*/(env +)?python[-0-9._]*( |$)"

It's no longer maintained but it's still a massive improvement over the defaults. It's fairly simple to install:

git clone https://github.com/nanorc/nanorc.git
cd nanorc
make install

Then nano ~/.nanorc and add:

include ~/.nano/syntax/ALL.nanorc