[Python] 執行 python 檔案出現奇怪的 env: python\r: No such file or directory 訊息

[Python] 執行 python 檔案出現奇怪的 env: python\r: No such file or directory 訊息

自己有個常用的 python script,平常都是用 python run.py 的方式在執行它,

今天想說這個 python 檔有在路徑 $PATH 裡面,而且也加了 x (執行) 的屬性,

就想說直接打 run.py 來跑跑看,首先出現了一些奇怪的錯誤:

testuser@localhost ~ $ run.py
/Users/testuser/run.py: line 1: import: command not found
/Users/testuser/run.py: line 2: import: command not found
/Users/testuser/run.py: line 3: import: command not found
from: can't read /var/mail/optparse
: command not found /Users/testuser/run.py: line 5:
from: can't read /var/mail/__init__
: command not found /Users/testuser/run.py: line 7:
/Users/testuser/run.py: line 8: syntax error near unexpected token `('

 

嗯… 雖然錯誤訊息看起來很奇怪,不過應該是因為沒有加 #! 的關係,

所以 Mac/Linux 會用 bash 來執行這個 python script…

在最前面加上 #!/usr/bin/env python 之後再執行,結果又變了:

testuser@localhost ~ $ run.py
env: python\r: No such file or directory

 

這個 python\r 是什麼東西?還真是一點頭緒都沒有…

直接執行 /usr/bin/env python 看起來又很正常:

testuser@localhost ~ $ /usr/bin/env python
Python 2.7.11 (default, Dec 22 2015, 10:50:41)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

 

到底是怎麼一回事呢?

上網查了一下,原來是因為我的 python 檔案一開始是在 Windows 上寫的,

所以 line ending 是 CRLF,這會導致 env 會把 CR (0d) 也當作是參數的一部分,

因此就變成 python + 0d 也就是 python\r 了~

用 hexdump 看一下就很清楚,python 後面有 0d 0a:

testuser@localhost ~ $ hexdump -C /Users/testuser/run.py
00000000  23 21 2f 75 73 72 2f 62  69 6e 2f 65 6e 76 20 70  |#!/usr/bin/env p|
00000010  79 74 68 6f 6e 0d 0a 0d  0a 69 6d 70 6f 72 74 20  |ython....import |
00000020  6f 73 0d 0a 69 6d 70 6f  72 74 20 73 68 75 74 69  |os..import shuti|
00000030  6c 0d 0a 69 6d 70 6f 72  74 20 75 72 6c 6c 69 62  |l..import urllib|
00000040  0d 0a 66 72 6f 6d 20 6f  70 74 70 61 72 73 65 20  |..from optparse |

 

解決方法就是把所有的 CRLF (0d 0a) 都換成 LF (0a),

一般來說在編輯器裡面可以將 line ending 設成 Unix 來達到,

例如我常用的 Sublime Text 可以選擇 View > Line Endings > Unix,

改好後再存檔,再看一次 hexdump 的結果,

果然 CRLF (0d 0a) 都被換成 LF (0a) 了:

testuser@localhost ~ $ hexdump -C /Users/testuser/run.py
00000000  23 21 2f 75 73 72 2f 62  69 6e 2f 65 6e 76 20 70  |#!/usr/bin/env p|
00000010  79 74 68 6f 6e 0a 0a 69  6d 70 6f 72 74 20 6f 73  |ython..import os|
00000020  0a 69 6d 70 6f 72 74 20  73 68 75 74 69 6c 0a 69  |.import shutil.i|
00000030  6d 70 6f 72 74 20 75 72  6c 6c 69 62 0a 66 72 6f  |mport urllib.fro|
00000040  6d 20 6f 70 74 70 61 72  73 65 20 69 6d 70 6f 72  |m optparse impor|

 

 再執行一次 run.py,一切都很正常了:

testuser@localhost ~ $ run.py
Usage: run.py [options]

 

參考資料:stackoverflow: env: python\r: No such file or directory 

(本頁面已被瀏覽過 2,818 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料