python 2 控制台传参,解包,编码问题初探
python 2 控制台传参,需要从sys模块中导入argv,argv返回的第一个参数当前脚本(script)的文件名,后面是参数,参数个数必须和解包(unpack)时使用的参数个数一致
1.本例子演示了Python 2 如何用控制台传入参数到脚本中去的过程
转载请声明本文的引用出处:仰望大牛的小清新
如下
#python 2
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from sys import argv
print "变量,解包,参数的练习" script, first, second, third = argv # unpack,运行时需要从控制台传入3个参数 print "This script is called: ", script
print "Your first variable is: ", first
print "Your second variable is : ", second
print "Your third variable is: ", third
传参如下
py -2 ex13.py variable1, "a string" 5
输出如图
可以看到,逗号也被作为参数输入了,而空格则没有,同时,字符串的输出也使用了默认的格式,参数被成功传入脚本。
2.关于传参数中输入中文会出错的问题
例子1中的代码在控制台输入中文时没有问题,但是如果使用formatters,例如%s,则会报错
对于这样的代码:
# python 2
#使用了formatters来输出中文, 会报错 script, user_name = argv
print "Hi %s, I'm the %s script." % (user_name, script)
会产生如下报错
python的默认编码格式可以在控制台进行查看和修改,方法如下
# python 2
# 获取Python解释器默认的编码方式并改变
import sys
print sys.getdefaultencoding() #输出默认编码
---------------------------------------------------------------
# 改变默认编码为utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
同时,用cmd输入中文,并将该输入写入文件也会出现乱码的情况,此时字符串的encode和decode方法均会报错,此时,上述reload sys的方法则可以有效解决这一问题,这里需要特别注意。
回到正题,然而,即便我设置了python解释器的默认编码,仍然产生上述报错,错误如下
这使我开始思考,恐怕我的系统默认字符集不是utf-8
于是我查看了系统的字符集,查看流程如下:
1.打开cmd
2.右键->属性
发现我的字符集是。。。GBK
这就很尴尬了。。。因此将编码修改为gbk,就ok了
完整代码如下:
# -*- coding: utf-8 -*-
# python 2
from __future__ import unicode_literals
print "raw_input 和 argv 混合使用" import sys
reload(sys)
sys.setdefaultencoding('gbk')# 我的系统默认的编码,也是cmd传参时使用的编码 from sys import argv
script, user_name = argv
prompt = '>' print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name
likes = raw_input(prompt) print "Where do you live %s?" % user_name
lives = raw_input(prompt) print "What kind of computer do you have?"
computer = raw_input(prompt) print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
3.如何不修改该源码直接设置python解释器的默认编码
我们可以在每个源码文件的开头直接设置编码为utf-8,但是我们也可以更加方便的直接将python的默认字符集从ascii改为utf-8
方法如下:
3.1首先,我们导入sys包,并通过sys包中的path寻找我们python解释器的lib所在路径
# -*- coding: utf-8 -*-
#python 2 import sys
print sys.path
在我的电脑上输出如下:
3.2检查输出,可以看到这里有 D:\\Program Files\\Python2\\lib。lib文件夹下的site.py里面的setencoding函数就是解决编码问题的关键。
默认的site.py文件中setencoding函数如下:
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
通过我们将encoding根据我们的需要改为utf-8,或者gbk,重启python解释器,即可更改默认设置,同时不需要修改代码
这个方法在工程中更为合适,避免因为一时疏忽而产生大量的报错信息
以更改为utf-8为例,更改后的setencoding如下
总共更改了2处:encoding和比较处的ascii为utf-8,在下面代码中以行末注释形式进行了提醒
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "utf-8" # Default value set by _PyUnicode_Init() #这里要改
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii": # 这里也要改
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
这样就可以避免在代码文件中重新加载sys模块进行设置了
4.文件输入输出中的编码问题
对于控制台传参,用上述方法就可以解决,但是对于文件输入输出的编码问题,仍不能这样解决
但是我们可以通过两种方式来解决,如下
# python 2
# 导入codecs模块,并使用模块中的open方法
import codecs
txt = codecs.open(filename,'r','utf-8') #------------------------------------------------------- # python 2
# 使用decode方法指定编码的解释方法
txt = open(filename)
print txt.read().decode('utf-8')
5.关于何时关闭文件句柄的问题
open(to_file,'w').write(open(from_file).read())#如果简写,那么我们不需要执行文件关闭操作
谢谢大家~~~撒花撒花*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。
python 2 控制台传参,解包,编码问题初探的更多相关文章
- Python中的传参是传值还是传址?
传值:在C++中,传值就是把一个参数的值给这个函数,其中的更改不会影响原来的值. 传址:即传引用,直接把这个参数的内存地址传递进去,直接去这个内存地址上进行修改. 但是这些在Python中都没有,Py ...
- Python菜鸟之传参
Python菜鸟之传参 : 看上面enroll( )函数的调用传参 enroll("twiggy","M",city="上海", age=2 ...
- 关于Python中包裹传参和解包裹的理解
1.包裹传参 首先思考一个问题:为什么要有包裹传参?原因包括但不仅限于以下两点:①不确定参数的个数.②希望函数定义的更加松散灵活 包裹传参分两种:包裹位置传参和包裹关键字传参.先看包裹位置传参: 在这 ...
- Python小技巧:使用*解包和itertools.product()求笛卡尔积
[问题] 目前有一字符串s = "['a', 'b'],['c', 'd']",想把它分开成为两个列表: list1 = ['a', 'b'] list2 = ['c', 'd'] ...
- Python 中星号作用:解包&打散
python中’*’和’**’的使用分两个方面,一个是计算,另一个是参数传递过程中元素的打包和解包. 计算方面 ‘*’和’**’在python中最常见的作用分别是‘相乘’和‘乘幂’,如下: > ...
- Python小技巧:使用*解包和itertools.product()求笛卡尔积(转)
leetcode上做提示时候看到有高人用这个方法解题 [问题] 目前有一字符串s = "['a', 'b'],['c', 'd']",想把它分开成为两个列表: list1 = [' ...
- 【原】Gradle调用shell脚本和python脚本并传参
最近由于项目自动化构建的需要,研究了下gradle调用脚本并传参的用法,在此作个总结. Pre build.gradle中定义了$jenkinsJobName $jenkinsBuild两个Jenki ...
- Python 序列与映射的解包操作
解包就是把序列或映射中每个元素单独提取出来,序列解包的一种简单用法就是把首个或前几个元素与后面几个元素分别提取出来,例如: first, seconde, *rest = sequence 如果seq ...
- Python 序列与映射的解包操作-乾颐堂
解包就是把序列或映射中每个元素单独提取出来,序列解包的一种简单用法就是把首个或前几个元素与后面几个元素分别提取出来,例如: first, seconde, *rest = sequence 如果seq ...
随机推荐
- CSS继承—深入剖析
CSS的继承是指被包在内部的标签将拥有外部标签的样式性质.继承特性最典型的应用通常发挥在整个网页的样式预设,即整体布局声明.而需要要指定为其它样式的部份设定在个别元素里即可达到效果.这项特性可以给网页 ...
- FAQ: SNMP on NetScaler Appliance
FAQ: SNMP on NetScaler Appliance https://support.citrix.com/article/CTX122436 https://docs.citrix.co ...
- AdjustTokenPrivileges启用权限
原文链接地址:http://blog.csdn.net/xbgprogrammer/article/details/7276760 我们有很多操作需要用到OpenProcess函数,而为了使程序 ...
- BZOJ2729 [HNOI2012]排队 【高精 + 组合数学】
题目链接 BZOJ2729 题解 高考数学题... 我们先把老师看做男生,女生插空站 如果两个老师相邻,我们把他们看做一个男生,女生插空站 对于\(n\)个男生\(m\)个女生的方案数: \[n!m! ...
- Substrings Sort string 基本操作
You are given nn strings. Each string consists of lowercase English letters. Rearrange (reorder) the ...
- json解析之jackson
对于json格式的数据解析现在越来越多了,之前介绍了两种:fastjson和net.sf.json解析. 今天又有一个jackson解析.不过相对于之前两种,这种感觉稍微笨拙些.呵呵,还是了解下吧: ...
- synchronized ---- 作用
获得同步锁: 1.清空工作内存: 2.从主内存拷贝对象副本到工作内存: 3.执行代码(计算或者输出等): 4.刷新主内存数据: 5.释放同步锁.
- CSS3奇偶选择器
.search-form td:nth-child(odd){//奇 width:100px; text-align:right;} .search-form td:nth-child(even){/ ...
- 有关getClassLoader().getResourceAsStream(fileName)、class.getResourceAsStream(fileName)和().getContextClassLoader().getResourceAsStream(fileName)的区别
一:前言 在自己获取属性时,碰见了XX.class.getResourceAsStream(fileName),自己对这个其实不是很理解,上网查了下资料,又看到了上述的几个,所以就研究了下. 二:内容 ...
- Spring - IoC(7): 延迟实例化
默认情况下,Spring IoC 容器启动后,在初始化过程中,会以单例模式创建并配置所有使用 singleton 定义的 Bean 的实例.通常情况下,提前实例化 Bean 是可取的,因为这样在配置中 ...