python学习之三

导入一些常用库和使用:

OS库

   getcwd -> 获取当前目录  chdir -> 改变当前目录  system  ->调用shell命令  (改变当前目录的目的就是可以在其他目录进行别的操作)

>>> import os
>>> os.getcwd()
'/home/lihe/hanxinsemi/trunk/sandbox/python'
>>> os.chdir('/home/lihe')
>>> os.system('mkdir today')
0
shutil 库

将 前者 复制成  后者 在当前目录, move操作将当前目录下的文件到别的目录下  是剪切的形式,不是复制!

>>> import shutil
>>> shutil.copyfile('test1.txt', 'test1.bak')
>>> shutil.move('test1.bak', './move')
glob库

搜索当前目录下该类型文件,并以list形式列出

>>> import glob
>>> glob.glob('*.txt')
['test1.txt', 'example.txt', 'test2.txt', 'test.txt']
sys库

取参数列表,就像mian(int argv, char **argc)一样 ,python也可以取出参数列表,比较方便!

$ ./test.py one two three
import sys
print sys.argv
['./test.py', 'one', 'two', 'three']

argparse库

类似用户友好命令行接口,可以提供help服务,可以对输入的参数列表进行处理,自动输出想要的结果,可以有默认的参数设置:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=min,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

$ ./test.py -h
usage: test.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
  N           an integer for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)
[lihe@hxsrv1 python]$ ./test.py 1 2 3 4
4
[lihe@hxsrv1 python]$ ./test.py 1 2 3 4 --sum
10
[lihe@hxsrv1 python]$ vi test.py 
[lihe@hxsrv1 python]$ ./test.py 1 2 3 4 
1
subprocess库

调用外部命令,比如shell脚本:

>>> import subprocess
>>> subprocess.call(["ls", "-l"])
total 44
-rw-rw-r-- 1 lihe lihe   59 Dec  6 17:45 example.txt
drwxrwxr-x 2 lihe lihe 4096 Dec 10 09:53 move
-rw-rw-r-- 1 lihe lihe  349 Dec 10 08:59 test1.txt
-rw-rw-r-- 1 lihe lihe   11 Dec 10 09:25 test2.txt
-rwxrwxr-x 1 lihe lihe 1008 Dec 10 10:26 test.py
-rw-rw-r-- 1 lihe lihe    0 Dec 10 08:32 test.txt
0
>>> subprocess.call("exit 1", shell=True)
1





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值