前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何把python2.x的脚本转为pyt

如何把python2.x的脚本转为pyt

作者头像
py3study
发布2020-01-06 14:18:15
4010
发布2020-01-06 14:18:15
举报
文章被收录于专栏:python3python3
  1. 利用Python内置(Python脚本)工具,帮你自动转换

Python 2.x版本,比如我安装的Python 2.7.2,其在windows下载安装好之后,就自带了相关的一些有用的工具。

其中一个叫做2to3.py,就是用来帮你实现,将Python 2.x的代码,转换为Python 3.x的代码的。

其位置位于:Python安装的根目录F:\Python34\Tools\Scripts\2to3.py

【如何利用2to3.py,实现将Python 2.x的代码,转换为Python 3.x的代码】     比如我手上有个Python 2.x的python脚本:

F:\GitHub\test.py

现在,想要将其转换为Python 3.x的代码。

可以通过打开windows的cmd,进入到python34的安装目录,F:\Python34\Tools\Scripts

A  按目录转换

假设我要转换的代码所在目录在:F:\GitHub

在cmd里面输入:

F:\Python34\Tools\Scripts>python 2to3.py -w F:\GitHub\

B 按指定代码转换

F:\Python34\Tools\Scripts>python 2to3.py -w F:\GitHub\test.py

即可成功转换,对应的执行结果:

此时,你可以看到原先的test.py,已经变成了Python 3.x的代码了。

对应的,也多出一个bak文件:test.py.bak,两者比较一下,即可看出区别:

当前,对于2to3.py本身,也可以通过help查看到更多的用法:

F:\Python34\Tools\Scripts\>python 2to3.py --help

Usage: 2to3 [options] file|dir ...

Options:

-h, --help            show this help message and exit

-d, --doctests_only   Fix up doctests only

-f FIX, --fix=FIX     Each FIX specifies a transformation; default: all

-j PROCESSES, --processes=PROCESSES

Run 2to3 concurrently

-x NOFIX, --nofix=NOFIX

Prevent a transformation from being run

-l, --list-fixes      List available transformations

-p, --print-function Modify the grammar so that print() is a function

-v, --verbose         More verbose logging

--no-diffs            Don't show diffs of the refactoring

-w, --write           Write back modified files

-n, --nobackups       Don't write backups for modified files

  -o OUTPUT_DIR, --output-dir=OUTPUT_DIR                 Put output files in this directory instead of                 overwriting the input files.  Requires -n.   -W, --write-unchanged-files                 Also write files even if no changes were required                 (useful with --output-dir); implies -w.   --add-suffix=ADD_SUFFIX                 Append this string to all output filenames. Requires                 -n if non-empty.  ex: --add-suffix='3' will generate                 .py3 files.

备注

(1)如果上述不加-w参数,则默认只是把转换过程所对应的diff内容打印输出到当前窗口而已。

(2)加了-w,就是把改动内容,写回到原先的文件了。

(3)不想要生成bak文件,再加上-n即可。

(4)不想看到那一堆输出的内容,加上–no-diffs,即可。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档