python 笔记 argv、open(filename)和.read()——12.25

习题 13:  参数、解包、变量

 

大体来说就是写个接受参数的脚本

argv  是所谓的“参数变量 (argument variable)”,是一个非常标准的编程术语。在其他的编程语言里你

也可以看到它。这个变量包含了你传递给  Python 的参数。

 

ex11.py

#-*- coding:utf-8-*-

 

from sys import argv  #其实就是允许使用argv这个内建变量,而import就是模组(modules)

 

script, first, second, third = argv

#解包,script是脚本(xxx.py)文件名

#first, second, third分别是第1,2,3个命令行参数

 

print "The script is called:", script

print "Your first variable is:", first

print "Your second variable is:", second

print "Your third variable is:",third

 

运行结果:

 python 笔记 argv、open(filename)和.read()——12.25

 

感悟与自我测试:

raw_input()与argv的区别:使用的时机不同,由以上例子可以看出,

argv是在在用户执行时候使用的。

raw_input()则是在使用中使用的。

以下进行合并测试:

 

ex13_1.py

#-*- coding:utf-8-*-

from sys import argv

 

script, first, second, third, fourth = argv

 

print "The script is called:",script

print "The first dog is called:", first

print "The second dog is called:", second

print "The third dog is called:", third

print "The fourth dog is called:", fourth

 

name =raw_input("What's you name?")

 

print "Oh, %r, your are so good!" %name

 

 

运行结果:

 python 笔记 argv、open(filename)和.read()——12.25

 

 

 

习题 14:  提示和传递

 

目标:

 

v 和 raw_input,为如何读写文件做基础

 

ex14.py

# -*- coding: utf-8-*-

from sys import argv

 

script,user_name = argv  #此处只定义一个,所以之后需要跟一个命令参数

prompt = '>'

prompt1 = '>>>>'

 

print "Hi %s, I'm the %s script." %(user_name, script)

#此处也很好理解,一个是我们跟的命令参数,

#一个是这个脚本的名称,此处为ex14.py

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(prompt1)

 

print "What kind of computer do you have?"

computer = raw_input(prompt)

 

print """

Alright, so you said %r about likingme.

You live in %r. Not sure where thatis.

And you have a %r computer. Nice.

""" %(likes , lives, computer)

 

运行结果:

 python 笔记 argv、open(filename)和.read()——12.25

 

 

 

 

 

习题 15:  读取文件

目标与感悟:

熟练使用

arg

学习使用

open(filename) 

 

.read()

sys

是一个代码库,from sys import argv是从sys代码库中提取内置的argv,所以后续无需再定义argv

 

ex15.py

# -*- coding:utf-8-*-

from sys import argv

 

script, filename = argv 

txt = open(filename)  #txt表示动作,打开filename

 

print "Here'syour file %r:" %filename #打印所跟的命令参数

print txt.read()   #理解为固定用法,读取txt的内容

 

print "Typethe filename again:" #询问是否再一次读取

file_again = raw_input(">") #>来引导输入,将输入的结果定义给file_again

 

txt_again = open(file_again) #将打开输入结果文件的动作定义给txt_again

 

printtxt_again.read()   #打印读取txt_again的内容

 

 

ex15_sample.txt

This is stuff Ityped into a file.

It is really coolstuff.

Lots and lots of funto have in here.

 

 

运行结果:

python 笔记 argv、open(filename)和.read()——12.25