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())#如果简写,那么我们不需要执行文件关闭操作

谢谢大家~~~撒花撒花*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。

最新文章

  1. Node.js学习笔记——Node.js开发Web后台服务
  2. MacBook安装双系统(Windows多分区)
  3. Grafana 安装
  4. iOS开发UI篇—IOS开发中Xcode的一些使用技巧
  5. openswitch db files
  6. SSIS 关于并发的两个设置
  7. python any()和all()用法
  8. HDU 小明A+B 2096
  9. Seedwork
  10. iOS开发——UI篇OC篇&UIDynamic详解
  11. NOI2010超级钢琴 2
  12. iOS开发进阶-实现多线程的3种方法
  13. 【翻译】理解Joomla!模板
  14. 遗传算法详解(LINGO及MatlabGA工具箱求解实现)
  15. Javascript高级编程学习笔记(80)—— 表单(8)表单序列化
  16. [CodeForces - 447A] A - DZY Loves Hash
  17. 【原创】标准HTTP请求工具类
  18. MyBatis.2剖析
  19. [USACO09NOV]硬币的游戏A Coin Game
  20. 【BZOJ】4129: Haruna’s Breakfast 树分块+带修改莫队算法

热门文章

  1. AngularJS设置文本样式小程序
  2. ECharts饼图制作分析
  3. Luogu2737 USACO4.1麦香牛块(动态规划)
  4. react router路由传参
  5. 【ZJ选讲·BZOJ 5073】
  6. string 类型转换
  7. 用PHP迭代器来实现一个斐波纳契数列
  8. JSR330的注解和spring的原生注解的比较
  9. 有关spring的各种下载资料的网站
  10. 对比append插入数据产生的redo量