【Linux/Ubuntu】Linux/Ubuntu运行python脚本

项目中需要在Linux上运行自己写的python脚本,特此记录一下操作流程,整个流程比较简单,这里我使用的版本是python3

  • 第一步:查看系统是否有python3
  • 第二步:编写python脚本
  • 第三步:运行python脚本
  • 问题解决:问题一
  • 问题解决:问题二
  • 问题解决:问题三
  • *以上就是python脚本在Linux中运行的步骤,如果喜欢,点个关注再走吧!!!!*

第一步:查看系统是否有python3

打开终端,输入:

python3

如果有python,会出现以下信息:

lcl@ubuntu:~$ python3
Python 3.6.9 (default, Mar 15 2022, 13:55:28)
[GCC 8.4.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.

第二步:编写python脚本

特别注意:python脚本的首行应加上如下代码:

#!/usr/bin/python

如果python中有中文,在代码中应加如下代码:

# -*- coding: utf-8 -*-

第三步:运行python脚本

cd到自己python脚本的目录下,然后 ./xxx.py 执行自己的脚本

cd textlicense/
./LicenseCheck.py 

注意:如果你的脚本是在windows下编写的,移动到Linux下,可能出现如下报错。

lcl@ubuntu:~$ cd textlicense/
lcl@ubuntu:~/textlicense$ ./LicenseCheck.py
bash: ./LicenseCheck.py: /usr/bin/python^M: bad interpreter: No such file or directory

问题解决:问题一

如果出现 bash: ./LicenseCheck.py: /usr/bin/python^M: bad interpreter: No such file or directory,说明当前脚本的属性是DOS,只有在Windows下可用,在Linux下不可用。
因此,如果需要在linux使用,需要将DOC格式转换为UNIX格式。
具体操作如下:
(1)终端中打开要运行的python文件

vi LicenseCheck.py

(2)输入如下命令查看文件格式

:set ff 或 :set fileformat 

(3)文档编辑器下面会出现

 fileformat=dos 或 fileformat=unix 

注意:fileformat=dos 说明,该文件只能在windows下运行,在linux下运行需要转换为unix格式(见(4))

(4)将文件格式修改为unix格式

:set ff=unix 或 :set fileformat=unix 

(5)保存退出

:wq

(6)在运行python脚本

问题解决:问题二

运行脚本时,出现TypeError: ‘encoding’ is an invalid keyword argument for this function的报错,错误原因:

    def logfile(self, text):
        with open('LicenseChecked.log', 'a+', encoding='utf-8') as f:
            t = time.strftime('%y-%m-%d %H:%M:%S')
            text = t + " " + text + '\n'
            f.write(text)
        f.close()
        return text

需要导入io模块,并且需要将:

(1)with open(‘LicenseChecked.log’, ‘a+’, encoding=‘utf-8’) as f:改为 with io.open(‘LicenseChecked.log’, ‘a+’, encoding=‘utf-8’) as f:
(2)f.write(text) 改为 f.write(text.decode(“utf-8”))

修改后如下所示:

	import io
    def logfile(self, text):
        with io.open('LicenseChecked.log', 'a+', encoding='utf-8') as f:
            t = time.strftime('%y-%m-%d %H:%M:%S')
            text = t + " " + text + '\n'
            f.write(text.decode("utf-8"))
        f.close()
        return text

ps:我也不知道,为什么装的python3,但是,执行却是按照python2的规则。

问题解决:问题三

运行执行脚本时出现:TypeError: write() argument 1 must be unicode, not str 报错,需要将:

f.write(text) 改为 f.write(text.decode(“utf-8”))
【 详 情 参 见 问 题 二 】

以上就是python脚本在Linux中运行的步骤,如果喜欢,点个关注再走吧!!!!

你可能感兴趣的:(linux,ubuntu,python)