python從命令行獲取參數操做

python從命令行獲取參數python

一: 簡單用法 從命令行獲取參數兩種方式: 一、經過sys.argv參數獲取:代碼以下:函數

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

import sys

#獲取輸入參數,對輸入參數進行分析

#第一種獲取輸入參數的方式  sys.agrv是一種list


print '輸入參數的個數爲:', len(sys.argv),'個'

print  '輸入的參數列表爲:' , str(sys.argv)

print  '輸出除了自己文件的其餘參數:',str(sys.argv[1:])


'''
測試結果:
ss:test wqp$ python inputargs.py arg2 arg3 arg4
輸入參數的個數爲: 4 個
輸入的參數列表爲: ['inputargs.py', 'arg2', 'arg3', 'arg4']
輸出除了自己文件的其餘參數: ['arg2', 'arg3', 'arg4']
ss:test wqp$ 
'''

note that:簡單說明以上代碼:命令行輸入的 參數的形式在python中是一個list,第一個參數是文件自己,若是想獲取除文件自己的參數,採用sys.argv[1:]獲取。測試

二、經過函數raw_input()獲取輸入參數:命令行

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

#raw_input()使用方法

age = raw_input('how old are you:')
height = raw_input('how tall are you :')
weight = raw_input('how much do you weigh:')

print 'so you are  %r old, %r tall, %r heavy'%(age,height,weight)

'''
輸出結果爲:
ss:test wqp$ python rawinput.py
how old are you:20
how tall are you :172cm
how much do you weigh:70
so you are  '20' old, '172cm' tall, '70' heavy
ss:test wqp$ 
'''
相關文章
相關標籤/搜索