python3学习笔记及常见问题

时间:2022-07-30 18:33:57

1,mac自带的python是2.7版本,我们需要按照python3,这样在terminal下可以直接使用,但是编译打包的时候会默认使用python2.7

解决办法:安装virtualenv,一个管理包的虚拟环境。

$ [sudo] pip install virtualenv
如果遇到错误:IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/virtualenv.py'

 解决:sudo chmod +a 'user:lichanghong allow add_subdirectory,add_file,delete_child,directory_inherit' /Library/python/2.7/site-packages/

1)virtualenv 的使用可以参考:http://www.cnblogs.com/tk091/p/3700013.html

  创建python3环境: virtualenv -p /usr/local/Cellar/python3/3.5.1/bin/python3  py

 

  启动:source activate

 关闭:deactivate

2,适配python2,3

import sys

if sys.version_info < (3, 0):

    # Python 2

    import Tkinter as tk

else:

    # Python 3

    import tkinter as tk


3,If you build with virtualenv --system-site-packages ENV
-------------------以上尝试能够行得通,但是在python3的环境下在pyinstaller里一直找不到tkinter,故改用cx_freeze

安装: pip3 install cx_freeze
cxfreeze hello.py --target-dir dist 编译到了dist
在cmd窗口输入cxfreeze-quickstart可以自动生成setup.py


例如:setup.py:
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(packages = ["os"], excludes = ["tkinter"])

import sys
base = 'Win32GUI' if sys.platform=='win32' else None

executables = [
Executable('my.py', base=base, targetName = 'my.app')
]

setup(name='testproj',
version = '1.0',
description = 'testproj 1.0 desc',
options = dict(bdist_exe = buildOptions),
executables = executables)


python setup.py bdist_msi
On Mac OS X, you can use bdist_dmg to build a Mac disk image.