21

I originally coded in python IDE on windows. Now when I pasted my code in a file on Linux server. Now when I run the script, it gives me this error:

bad interpreter: No such file or directory

Please tell how to resolve this error.

Rahn
  • 4,787
  • 4
  • 31
  • 57
Deepak
  • 373
  • 1
  • 2
  • 7

2 Answers2

35

Probably you have \r\n line endings, where \r is carriage return and \n is newline

That means that the first line might be like this

#!/usr/bin/env python\r\n

or

#!/usr/bin/python\r\n

so the shell is trying to run the command python\r

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • I'm not aware of any recent versions of sh/bash/dash/ksh that behave this way – KingRadical May 26 '13 at 09:18
  • It's actually the kernel itself that handles this, not the shell. And yes, this is a possibility. – Cairnarvon May 26 '13 at 11:17
  • 2
    +1 I'm pretty sure this is the explanation. – tripleee May 26 '13 at 12:28
  • `vi` has a "dos-mode". If it's creating a file like that, you've probably got something in your `.virc` that's turning it on by default. [This may help](http://stackoverflow.com/questions/82726/convert-dos-line-endings-to-linux-line-endings-in-vim) – John La Rooy Jun 10 '14 at 21:20
  • same problem, I resolved it using dos2unix file.py to convert newline chars. – rubenafo Jul 21 '14 at 14:38
13

You're probably using the #!python hashbang convention that's inexplicably popular among Windows users. Linux expects a full path there. Use either #!/usr/bin/python or (preferably) #!/usr/bin/env python instead.

Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
  • 1
    would be preferable in some cases to use `#!python` because it takes python from the path - e.g. to be executed in the context of a `venv`. – Blake Mar 30 '17 at 11:53
  • A workaround is to open the file in xed editor (linux mint default text editor) Choose Save As and in the Line Ending drop down menu on the bottom, choose Unix/Linux instead of windows. This will clear up the line ending incompatibilities. – gxpr Apr 18 '18 at 16:15
  • Today I learned about `#!python` – Andrew Keeton May 30 '19 at 17:43