A strange error on running Python script at the shell

Problem

I have a Python script named foo.py. Since, I would like to run it directly from the shell, I have added a shebang to run it through Python:

#!/usr/bin/env python
print "Hello world"

If I run it directly at the shell, I get a strange error:

$ ./foo.py
: No such file or directory

However, if I run it explicitly with the Python interpreter, it works fine:

$ python foo.py
Hello world

Solution

This strange error turned out to be due to the newline markers in the file. The file was created on Windows and had CR+LF as the newline marker. But, I was running the script on Linux, which only uses LF as the newline marker.

So, this must have led the env program to run the character CR as a command. And obviously, it could not find any such file or directory.

The solution is simple. Convert the newline markers in the file to that of the host system, in this case to Linux. This can be done easily in Vim by using the fileformat option.

Tried with: GNU CoreUtils 8.12.197, Python 2.7.3 and Ubuntu 12.04 LTS

Advertisements

One thought on “A strange error on running Python script at the shell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s