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

本文详细介绍了在Linux环境下安装和运行Python3脚本的步骤,包括检查Python版本、脚本编码问题、DOS与UNIX格式转换,以及TypeError的解决。确保脚本在Linux中顺利运行并提供了解决常见问题的方法。
摘要由CSDN通过智能技术生成

第一步:查看系统是否有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中运行的步骤,如果喜欢,点个关注再走吧!!!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

米码收割机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值