Learn Python The Hard Way(13)

本文介绍了一种通过命令行传递参数到Python脚本的方法,并演示了如何使用sys模块的argv来接收这些参数。通过实例展示了如何定义并打印出传入的四个参数。

In this exercise we will cover one more input method you can use to pass variables to a script (script being another name for your .py files). You know how you typepython ex13.py to run the ex13.py file? Well the ex13.py part of the command is called an "argument". What we'll do now is write a script that also accepts arguments.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sys import argv
script,first,second,third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third

result:

                                    141555_8dbu_189901.jpg

On line 1 we have what's called an "import". This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts as documentation for other programmers who read your code later. The argv is the "argument variable", a very standard name in programming. that you will find used in many other languages. This variable holds the arguments you pass to your Python script when you run it. In the exercises you will get to play with this more and see what happens.

Line 3 "unpacks" argv so that, rather than holding all the arguments, it gets assigned to four variables you can work with: script, first, second, and third. This may look strange, but "unpack" is probably the best word to describe what it does. It just says, "Take whatever is in argv, unpack it, and assign it to all of these variables on the left in order." 

After that we just print them out like normal.

Hold Up! Features Have Another Name

I call them "features here" (these little things you import to make your Python program do more) but nobody else calls them features. I just used that name because I needed to trick you into learning what they are without jargon. Before you can continue, you need to learn their real name: modules. From now on we will be calling these "features" that we import modules. I'll say things like, "You want to import the sys module." They are also called "libraries" by other programmers, but let's just stick with modules





转载于:https://my.oschina.net/xtfjt1988/blog/401822

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值