在做一个小项目时,正好有需求要去获取指定目录的SVN相关信息,初始第一版code如下所示:
import os, re, traceback, subprocess, tempfile
def getSvnInfo(path):
try:
cur_path = os.getcwd()
os.chdir(path)
# 使用如下接口很方便的去获取SVN INFO相关信息
rt = os.popen('svn info').read()
os.chdir(cur_path)
except Exception as e:
print('str(Exception):', str(Exception))
print('repr(e):', repr(e))
print('traceback.format_exc(): %s' % traceback.format_exc())
return rt
if __name__ == '__main__':
print(getSvnInfo('./'))
获取的信息如下所示:
Path: .
Working Copy Root Path: I:\svn
URL: file:///H:/mysvn/pytools
Relative URL: ^/pytools
Repository Root: file:///H:/mysvn
Repository UUID: 060fed93-8902-9345-9e49-db05ad847e58
Revision: 79
Node Kind: directory
Schedule: normal
Last Changed Author: xsophiax
Last Changed Rev: 79
Last Changed Date: 2019-04-07 16:13:26 +0800 (周日, 07 四月 2019)
如上所述,使用Python直接执行是没有任何问题的,但是心细的同学发现返回的Result存在中文;
此时放心的过滤,直接使用pyinstaller -F lesson_subprocess.py,直接运行则出现如下问题(汗一个):
查.......查... ...
太过简单的调用os.popen('svn info').read(),其返回的含有中文,则open时encoding则要采用‘gbk’呀;
这样岂不是不能这么快乐采用这种方式了... ...
查看源码,参照改一下,如下所示:
def getSvnInfo(path):
try:
cur_path = os.getcwd()
os.chdir(path)
with tempfile.TemporaryFile(mode='w+', encoding='gbk') as out_temp:
fileno = out_temp.fileno()
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen('svn info', stdin=subprocess.DEVNULL, stdout=fileno, stderr=fileno, startupinfo=si)
p.wait()
out_temp.seek(0)
rt = out_temp.read()
os.chdir(cur_path)
print(rt)
except Exception as e:
print('str(Exception):', str(Exception))
print('repr(e):', repr(e))
print('traceback.format_exc(): %s' % traceback.format_exc())
return rt
这直接运行就能正常显示结果了,如下图所示: