python学习笔记
1、下载安装插件
1.1 pip install 某某插件
例如:pip install redis
python一般在环境变量中添加两个路径:
D:\Programs\Python\Python36\;
D:\Programs\Python\Python36\Scripts\;
pip.exe和easy_install.exe都在Python\Python36\Scripts\;路径下。
在开发游戏db系统的时候,因为内网没有连接互联网,不能直接使用pip来安装redis库。所以我在外网pip install redis以后,再将“Python\Python36\Lib\site-packages”路径下,redis相关的文件打包,拷贝到内网python对应目录下,redis插件就可以使用了。
- windows下安装psutil模块:“pip3.exe install psutil”
2、定义一个函数,用def关键字。可在函数中对参数类型做检查:
- if not isinstance(x,(int,double)):并用raise来抛出异常日志。
def my_abs(x):
if not isinstance(x,(int,double)):
raise TypeError(' Bad Type Error.')
if(x<0):
return -x;
else:
return x;
print my_abs('a')
print my_abs(-10)
3、定义一个空函数,pass类似于C++的return
def my_empty():
pass
print my_empty()
4、安装pyUserInput
- 1.一开始安装pyUserInput时报错,原因:电脑是64位的,安装python3.7 64位版本导致,需要先安装pyHook
- 2.安装pyHook:将安装包下载到本地进行安装,我电脑是64位,python3.7版本
- 资源地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
需要与系统、python版本对应
执行命令:pip3 install pyHook-1.5.1-cp37-cp37m-win_amd64.whl
- 资源地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
- 3.安装好pyHook以后,此时可尝试安装pyUserInput
- 执行命令:pip install pyUserInput
- 4.安装pyUserInput时,会自动安装pywin32。如果安装过程中出现错误,如read timed out,是网速不好导致pyUserInput安装失败,可以将pywin32下载到本地进行安装,在进行pyUserInput的安装,安装pywin32请参考下面步骤
- 安装pywin32
- 网址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
- 将安装包下载到本地进行安装,此处注意选择的版本一定要和python版本一致
执行命令:pip install pywin32-227-cp37-cp37m-win_amd64.whl。
再安装pyUserInput就很快了
5、python3和python2一起安装
- 将python3安装路径下的python.exe重命名为python3.exe,Python2安装路径下的python.exe重命名为python2.exe,然后把2个路径都配置到环境变量path中。
- python3运行脚本的话,就在cmd中输入:python3 xxx.py
- python2运行脚本的话,就在cmd中输入:python2 xxx.py
6、python2注册到注册表中
新建脚本:register.py,输入内容
import sys
from _winreg import *
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
installpath, installpath, installpath
)
def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print "*** Unable to register!"
return
print "--- Python", version, "is now registered!"
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register!"
print "*** You probably have another Python installation!"
if __name__ == "__main__":
RegisterPy()
然后在cmd中运行该脚本:python2 register.exe