Python–cookbook–13.脚本编程与系统管理

Python–cookbook–13.脚本编程与系统管理

相关介绍

import fileinput
import sys
import argparse
import getpass
import os
import subprocess
import shutil
import time
from configparser import ConfigParser
import webbrowser


# 通过重定向/管道/文件接受输入
# with fileinput.input() as f:
#     for line in f:
#         print(f.filename(), f.lineno(), line, end='')

# 终止程序并给出错误信息
# sys.stderr.write('It failed!\n')
# a = 2
# raise SystemExit(a)  # 给返回码

# 解析命令行选项
# parser = argparse.ArgumentParser(description='Search some files')
# parser.add_argument(dest='filenames', metavar='filename', nargs='*')
# parser.add_argument('-p', '--pat', metavar='pattern', required=True,
#                     dest='patterns', action='append',
#                     help='text pattern to search for')
# parser.add_argument('-v', dest='verbose', action='store_true',
#                     help='verbose mode')
# parser.add_argument('-o', dest='outfile', action='store',
#                     help='output file')
# parser.add_argument('--speed', dest='speed', action='store',
#                     choices={'slow', 'fast'}, default='slow',
#                     help='search speed')
# args = parser.parse_args()
# #Output the collected arguments
# print(args.filenames)
# print(args.patterns)
# print(args.verbose)
# print(args.outfile)
# print(args.speed)

# 运行时弹出密码输入提示 (需要terminal运行)
# user = getpass.getuser()
# user = input("User:")
# passwd = getpass.getpass("PassWord:")
# print(user)
# print(passwd)
# if svc_login(user, passwd): # You must write svc_login()
#     print('Yay!')
# else:
#     print('Boo!')

# 获取终端的大小
# sz = os.get_terminal_size() # 猜测适用于linux

# 执行外部命令并获取它的输出
# text = b'''
# hello world
# this is a test
# goodbye
# '''
# # Launch a command with pipes
# p = subprocess.Popen(['wc'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
# # Send the data and get the output
# stdout, stderr = p.communicate(text)
# # To interpret as text, decode
# out = stdout.decode('utf-8')
# err = stderr.decode('utf-8')

# 赋值或者移动文件和目录
# # Copy src to dst. (cp src dst)
# shutil.copy(src, dst)
# # Copy files, but preserve metadata (cp -p src dst)
# shutil.copy2(src, dst)
# # Copy directory tree (cp -R src dst)
# shutil.copytree(src, dst, ignore=shutil.ignore_patterns('*~', '*.pyc'))
# # Move src to dst (mv src dst)
# shutil.move(src, dst)


# 创建和解压归档文件
# shutil.make_archive('py33', 'zip', 'test') # 文件名、压缩格式、被压缩文件
# shutil.unpack_archive('py33.zip')

# 通过文件名查找文件
# def modified_within(top, seconds):
#     now = time.time()
#     for path, dirs, files in os.walk(top):
#         for name in files:
#             fullpath = os.path.join(path, name)
#             if os.path.exists(fullpath):
#                 mtime = os.path.getmtime(fullpath)
#                 if mtime > (now - seconds):
#                     print(fullpath)
#
# if len(sys.argv) != 3:
#     print('Usage: {} dir seconds'.format(sys.argv[0]))
#     raise SystemExit(1)
# modified_within(sys.argv[1], float(sys.argv[2]))

# 读取配置文件
# prefix=/usr/local
# prefix: /usr/local 等效
# 配置文件中的名字是不区分大小写的
# cfg = ConfigParser()
# cfg.read('config.ini')
# print(cfg.sections())
# print(cfg.get('installation', 'library'))
# print(cfg.getboolean('debug', 'log_errors'))
# print(cfg.getint('server', 'port'))
# print(cfg.get('server', 'signature'))
#
# cfg.set('server', 'port', '9000')
# cfg.set('debug', 'log_errors', 'False')
# cfg.write(sys.stdout)

# 实现一个计时器
# class Timer:
#     def __init__(self, func=time.perf_counter):  # time.perf_counter比time.time更精确
#         self.elapsed = 0.0
#         self._func = func
#         self._start = None
#     def start(self):
#         if self._start is not None:
#             raise RuntimeError('Already started')
#         self._start = self._func()
#     def stop(self):
#         if self._start is None:
#             raise RuntimeError('Not started')
#         end = self._func()
#         self.elapsed += end - self._start
#         self._start = None
#     def reset(self):
#         self.elapsed = 0.0
#
#     @property
#     def running(self):
#         return self._start is not None
#     def __enter__(self):
#         self.start()
#         return self
#     def __exit__(self, *args):
#         self.stop()
#
# def countdown(n):
#     while n > 0:
#         n -= 1
# t = Timer()
# t.start()
# countdown(1000000)
# t.stop()
# print(t.elapsed)
#
# with t:
#     countdown(1000000)
# print(t.elapsed)
#
# with Timer() as t2:
#     countdown(1000000)
# print(t2.elapsed)

# 启动一个web浏览器
# webbrowser.open('http://www.python.org')
# # Open the page in a new browser window
# webbrowser.open_new('http://www.python.org')
# # Open the page in a new browser tab
# webbrowser.open_new_tab('http://www.python.org')
#
# c = webbrowser.get('firefox')
# c.open('http://www.python.org')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柴寺仓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值