@app.route('/convert')
def convert():
file_path = request.args.get('path')
file_name = file_path.split('/')[-1]
short_name = os.path.splitext(file_name)[0]
file_dir = file_path[:file_path.index(file_name)]
cmd = 'pdf2htmlEX --zoom 1.3 --dest-dir "%s" "%s" "%s" ' % (file_dir, file_path, short_name+'.html')
status = os.popen(cmd)
以上代码是flask的一个小程序,当代码执行到os.popen(cmd)时,由于cmd中包含有中文,会报UnicodeEncodeError: ‘ascii’ codec can’t encode错误。
解决办法:
Python2默认编码是ascii,由此Python自然调用ascii编码解码程序去处理字符流,当字符流不属于ascii范围内,就会抛出异常。
解决的方案很简单,修改默认的编码模式
文件开头加入一下三行代码
import sys
reload(sys)
sys.setdefaultencoding('utf-8')