目录
获取和编辑windows系统环境变量
1.新增的系统变量使用下面的方法获取不到,关机重启即可
2.修改的环境变量是临时改变的,当程序停止时修改的环境变量失效(系统变量不会改变)
# 获取 系统环境 PATH 的变量
# env = os.environ.get("PATH")
print os.environ["PATH"]
# 定义环境变量
mydir = "c:\\mydir"
# 给 MYDIR赋值(临时创建的环境变量)
os.environ["TERM"] = mydir+";" + os.environ["TERM"]
print os.environ["TERM"]
可以修改path路径的显示方式,便于查看
In [6]: print('\n'.join(os.environ["path"].split(';')))
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
C:\windows\system32
C:\windows
C:\windows\System32\Wbem
C:\windows\System32\WindowsPowerShell\v1.0\
D:\Program Files\Java\jdk1.8.0_181\bin
D:\Program Files\MySQL\MySQL Server 5.5\bin
D:\Program Files\apache-ant-1.9.3/bin
C:\Program Files (x86)\Google\Chrome\Application
D:\Programs\TortoiseSVN\bin
D:\Programs\Python\Python 3.7.2\Scripts\
D:\Programs\Python\Python 3.7.2\
D:\Programs\JetBrains\PyCharm 2018.3.5\bin
修改标准输出编码
方法一
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
此语句重复执行两次之后,执行输入输出操作会报错
ValueError: I/O operation on closed file.
方法二
import sys
import io
def setup_io():
#sys.stdout 是个 io.TextIOWrapper,有个 buffer 属性,里边是个 io.BufferedWriter。
sys.stdout = sys.__stdout__ = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8', line_buffering=True)
sys.stderr = sys.__stderr__ = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8', line_buffering=True)
setup_io()
经验证执行多次,仍可正常输出
----------
转自:python3 Xcode环境 中文输出问题临时解决
作者:yuanzhiying
出处:简书
调试字符串编码
1. 保证控制台编码和基本输出编码sys.stdout.encoding一致
当需要查看某个字符在经过某种编码之后的显示结果时,需要保证控制台编码和基本输出编码sys.stdout.encoding一致
否则无法得到正确的结果,如修改sys.stdout.encoding之后,执行print()函数
In[24]: sys.stdout = sys.__stdout__ = io.TextIOWrapper(sys.stdout.detach(), encoding='gbk', line_buffering=True)
In[25]: print("你好")
���
In[26]: '异常'.encode("gbk").decode("gbk")
Out[26]: '�쳣'
In[27]: '异常'.encode("utf-8").decode("gbk")
Out[27]: '异常'
尽管'异常'.encode('gbk').decode('gbk')正确无误,然而显示的结果却让人大跌眼镜
原因就在于该语句执行之后,会得到unicode编码的字符串,python会对该字符串以sys.stdout.encoding编码,再由控制台解码
该语句完整过程如下:
'异常'.encode('gbk').decode('gbk').encode('gbk').decode('utf-8',"ignore")
# 结果为乱码:'�쳣'
'异常'.encode('utf-8').decode('gbk').encode('gbk').decode('utf-8')
# 结果正常:'异常'
2. 控制台最好选择与unicode相对应的utf-8编码
除了保证编码一致之外,最好选择与unicode相对应的utf-8,否则某些字符在指定编码下,会无法编码/解码,导致显示异常
>>> '忧郁的乌龟'.encode('big5')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'big5' codec can't encode character '\u5fe7' in position 0:
illegal multibyte sequence
>>> '憂鬱的烏龜'.encode('gb2312')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'gb2312' codec can't encode character '\u6182' in position 0:
illegal multibyte sequence
获取系统编码的相关函数和属性
Python的缺省编码:sys.getdefaultencoding() # Python环境系统默认编码 解释器会用到,python将binary data转换为str的默认编码方法
系统当前的编码:locale.getdefaultlocale() # 操作系统当前编码 是getpreferredencoding的父集
本地首选编码:locale.getpreferredencoding() # 默认为打开本地操作系统读取的文本文件的编码方式,因操作系统而异,除非指定
临时更改本地编码(通过locale.setlocale(locale.LC_ALL,“zh_CN.UTF-8″)):locale.getlocale()
文件系统的编码:sys.getfilesystemencoding() # 文件编码,Python编码解码文件名,调用操作系统文件API
终端的输入编码:sys.stdin.encoding # 输入编码 input()会用到,PYTHONIOENCODING 变量指定
终端的输出编码:sys.stdout.encoding # 输出编码 print()会用到,PYTHONIOENCODING 变量指定
代码的缺省编码:# -*- coding: utf-8 –*- # 文件开头,指定python解译器编码
查看字符串的unicode编码
无法直接使用unicode这种编码格式
>>> '你好'.encode("unicode")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: unknown encoding: unicode
可以使用unicode-escape是将字符以unicode内存编码进行编码
>>> '你好'.encode("unicode-escape")
b'\\u4f60\\u597d'
字符可以直接采用‘\uxxxx’的形式来表示,例如‘\ufffd’和‘�’两种方式表示字符串是等价的
>>> '中国'=='\u4e2d\u56fd'
True
另外,b“xxx”只支持ascii码字符自动转换为bytes,使用 b‘\uxxxx’也可以完成自动转换
In[27]: b1=b'\ufffd' # 特殊字符‘�’unicode字节序列
In[28]: b1
Out[28]: b'\\ufffd'
In[29]: b2='\ufffd'.encode("unicode-escape") # 特殊字符�进行unicode编码
In[30]: b2
Out[30]: b'\\ufffd'
In[31]: b1==b2 # 比较直接定义和编码后的结果是否一致
Out[31]: True
Python IDEL执行print函数反常情况
在 IDEL无法直接换行,末尾要加上“;”或者“\”,使用注释也问题颇多
>>> import sys;\
import locale;\
\
print("sys:");\
print("sys.getdefaultencoding():",sys.getdefaultencoding());\
print("sys.getfilesystemencoding():",sys.getfilesystemencoding());\
print();\
\
print("local:");\
print("locale.getpreferredencoding():",locale.getpreferredencoding());\
print("locale.getdefaultlocale():",locale.getdefaultlocale());\
print();\
\
print("sys.stdout:");\
print("sys.stdin.encoding:",sys.stdin.encoding);\
print("sys.stdout.encoding:",sys.stdout.encoding);\
print();\
\
print('中文');\
print('\ufffd');\
print('\u00bb');\
print()
输出结果:
sys:
sys.getdefaultencoding(): utf-8
sys.getfilesystemencoding(): utf-8
local:
locale.getpreferredencoding(): cp936
locale.getdefaultlocale(): ('zh_CN', 'cp936')
sys.stdout:
sys.stdin.encoding: cp936
sys.stdout.encoding: cp936
中文
�
»
print('\ufffd') # 对应unicode字符‘�’
print('\u00bb') # 对应unicode字符‘»’
两者皆不能用gbk进行编码,而print函数却输出了正常结果!!!
print函数没有使用sys.stdout.encoding进行编码?
查看模块的具体位置
可以通过通过属性__file__查看模块具体位置
>>> import http.server
>>> http.server.__file__
'D:\\Programs\\Python\\Python 3.7.2\\lib\\http\\server.py'
>>> import pygame.examples.aliens
pygame 1.9.5
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.examples.aliens.__file__
'D:\\Programs\\Python\\Python 3.7.2\\lib\\site-packages\\pygame\\examples\\aliens.py'
获取当前目录和上级路径
可以借助python os模块的方法对目录结构进行操作
import os
print '***获取当前目录***'
print os.getcwd()
print os.path.abspath(os.path.dirname(__file__))
print '***获取上级目录***'
print os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
print os.path.abspath(os.path.dirname(os.getcwd()))
print os.path.abspath(os.path.join(os.getcwd(), ".."))
print '***获取上上级目录***'
print os.path.abspath(os.path.join(os.getcwd(), "../.."))
#获取上次取决于../../..个数,列如这样就是上上上层
终端中执行时,文件的相对路径起始为命令执行的路径
文件中执行时,起始相对路径是被执行文件的所在路径
os.getcwd() ——命令执行的路径(终端可直接执行)
os.path.dirname(__file__) ——被执行文件的所在路径(写在执行文件代码中)
os.path.join(os.getcwd(),"data/train2.txt") ——拼接目录和文件,形成完整绝对路径
注: 区别 sys.path 和 os.path
sys.path是python模块搜索的路径,类型是列表<type 'list'>
os.path是python操作文件路径的模块,类型是模块<type 'module'>
摘自:python获取当前目录路径和上级路径
作者:lkning
出处:简书