解决Linux下运行Python脚本显示“: 没有那个文件或目录”的问题

来源:互联网 发布:淘宝客推广在哪里展示 编辑:程序博客网 时间:2024/05/21 03:55

解决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()

运行以上脚本对文本的换行符进行替换后,原来不能直接运行的脚本现在可以直接运行了:

arthus@arthus-desktop:~/桌面$ ./test.py PythonTest.py 

Reading file PythonTest.py

Writing file PythonTest.py

Replace for PythonTest.py successfully

arthus@arthus-desktop:~/桌面$ ./PythonTest.py 

This is just a test!


原创粉丝点击