解決Linux下執行Python指令碼顯示“: 沒有那個檔案或目錄”的問題
我猜不少人都遇到過類似的問題:
在Windows下寫好了一個python指令碼,執行沒問題
但放到Linux系統下就必須在命令列前加上一個python直譯器才能執行
指令碼開頭的註釋行已經指明瞭直譯器的路徑,也用chmod給了執行許可權,但就是不能直接執行指令碼。
比如這個指令碼:
#!/usr/bin/env python
#-*- coding=utf-8 -*-
def main():
print('This is just a test!\r\n')
if __name__ == '__main__':
main()
按理說沒錯的,但為什麼不能直接執行呢?
後來發現問題出在換行表示上……
Windows下,文字的換行是\r\n一同實現的,而*nix下則只用\n
所以我的第一行程式碼在Linux下就被識別為了:
#!/usr/bin/env python\r
很顯然,系統不知道這個"python\r"是個什麼東西……
知道了這個,解決方案就很顯而易見了,寫了一個自動替換換行標誌的指令碼:
#!/usr/bin/env python
#-*- coding=utf-8 -*-
import sys, os
def replace_linesep(file_name):
if type(file_name) != str:
raise ValueError
new_lines = []
#以讀模式開啟檔案
try:
fobj_original = open(file_name, 'r')
except IOError:
print('Cannot read file %s!' % file_name)
return False
#逐行讀取原始指令碼
print('Reading file %s' % file_name)
line = fobj_original.readline()
while line:
if line[-2:] == '\r\n':
new_lines.append(line[:-2] + '\n')
else:
new_lines.append(line)
line = fobj_original.readline()
fobj_original.close()
#以寫模式開啟檔案
try:
fobj_new = open(file_name, 'w')
except IOError:
print('Cannot write file %s!' % file_name)
return False
#逐行寫入新指令碼
print('Writing file %s' % file_name)
for new_line in new_lines:
fobj_new.write(new_line)
fobj_new.close()
return True
def main():
args = sys.argv
if len(args) < 2:
print('Please enter the file names as parameters follow this script.')
os._exit(0)
else:
file_names = args[1:]
for file_name in file_names:
if replace_linesep(file_name):
print('Replace for %s successfully!' % file_name)
else:
print('Replace for %s failed!' % file_name)
os._exit(1)
if __name__ == '__main__':
main()
執行以上指令碼對文字的換行符進行替換後,原來不能直接執行的指令碼現在可以直接運行了:
[email protected]:~/桌面$ ./test.py PythonTest.py
Reading file PythonTest.py
Writing file PythonTest.py
Replace for PythonTest.py successfully!
[email protected]:~/桌面$ ./PythonTest.py
This is just a test!