打造命令行工具
from __future__ import print_function import sys print(sys.argv)
在终端执行命令会打印跟这的参数
sys.argv是一个保存命令行参数的普通列表。因为他是一个普通的列表,所以我们可以直接修改sys.argv的内容
demo

from __future__ import print_function import os import sys def main(): sys.argv.append("") filename = sys.argv[1] if not os.path.isfile(filename): raise SystemError(filename + "dose not exists") # 是否有访问权限 elif not os.access(filename, os.R_OK): raise SystemError(filename, " is not accessible") else: print(filename, " is accessible") if __name__ == '__main__': main()
使用sys.stdin和fileinput读取文件标准输入

from __future__ import print_function import sys for line in sys.stdin: print(line, end=" ") def get_content(): return sys.stdin.readlines() print(get_content())
使用fileinput读取文件内容

from __future__ import print_function import fileinput for line in fileinput.input(): meta = [fileinput.filename(), fileinput.fileno(), fileinput.filelineno(), fileinput.isfirstline(), fileinput.isstdin()] print(*meta, end=" ") print(line, end=" ")
使用SystemExit异常打印错误信息
import sys sys.stdout.write("hello") sys.stdeer.write("world")
用户错误的输出,和标准的输出
使用getpass库获取密码

from __future__ import print_function import getpass user = getpass.getuser() passwd = getpass.getpass() print(user, passwd)
使用ConfigParse解析配置文件

import configparser cf = configparser.ConfigParser(allow_no_value=True) cf.read("./my.cnf") """ sections() Return all the configuration section names, sans DEFAULT. has_section(section) Return whether the given section exists. has_option(section, option) Return whether the given option exists in the given section. options(section) Return list of configuration options for the named section. read(filenames, encoding=None) Read and parse the list of named configuration files, given by name. A single filename is also allowed. Non-existing files are ignored. Return list of successfully read files. read_file(f, filename=None) Read and parse one configuration file, given as a file object. The filename defaults to f.name; it is only used in error messages (if f has no `name' attribute, the string `<???>' is used). read_string(string) Read configuration from a given string. read_dict(dictionary) Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. get(section, option, raw=False, vars=None, fallback=_UNSET) Return a string value for the named option. All % interpolations are expanded in the return values, based on the defaults passed into the constructor and the DEFAULT section. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents override any pre-existing defaults. If `option' is a key in `vars', the value from `vars' is used. getint(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to an integer. getfloat(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to a float. getboolean(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to a boolean (currently case insensitively defined as 0, false, no, off for False, and 1, true, yes, on for True). Returns False or True. items(section=_UNSET, raw=False, vars=None) If section is given, return a list of tuples with (name, value) for each option in the section. Otherwise, return a list of tuples with (section_name, section_proxy) for each section, including DEFAULTSECT. remove_section(section) Remove the given file section and all its options. remove_option(section, option) Remove the given option from the given section. set(section, option, value) Set the given option. write(fp, space_around_delimiters=True) Write the configuration state in .ini format. If `space_around_delimiters' is True (the default), delimiters between keys and values are surrounded by spaces. """
使用ArgumentParse解析器

from __future__ import print_function import argparse def _argparse(): parser = argparse.ArgumentParser(description="This is description") parser.add_argument("--host", action="store", dest="server", default="localhost", help="connect to host") parser.add_argument("-t", action="store_true", default=False, dest="boolean_switch", help="set switch to true") return parser.parse_args() def main(): parse = _argparse() print(parse) print("host = ", parse.server) print("boolean_switch=", parse.boolean_switch) if __name__ == '__main__': main()
模拟数据库客户端命令行参数

from __future__ import print_function import argparse def _argparse(): parser = argparse.ArgumentParser(description="A Python-Mysql client") parser.add_argument("--host", action="store", dest="host", required=True, help="connect to host") parser.add_argument("-u", "--user", action="store", dest="password", required=True, help="password to use when connecting to server") parser.add_argument("-p", "--password", action="store", dest="password", required=True, help="password to use") def main(): parser = _argparse() conn_args = dict(host=parser.host, user=parser.user) print(conn_args) if __name__ == '__main__': main()
logging模块

import logging logging.basicConfig( level=logging.DEBUG, format="%(asctime)s : %(levelname)s : %(message)s", filename="app.log" ) logging.debug("debug") logging.info("info") logging.warn("warn") logging.error("error") logging.critical("critical")
使用click解析命令行参数
pip install click
1,@click.command()装饰一个函数,使之成为命令行接口
2,@click.option()等装饰函数,为其添加命令行选项等。

import click @click.command() @click.option("--count", default=1, help="Number of greetings.") @click.option("--name", prompt="your name", help="The person to greet.") def hello(count, name): for x in range(count): click.echo("Hello %s!" % name) if __name__ == '__main__': hello()