Skip to content

命令行(Python)

sys.argv

import os
import sys

def main():
    sys.argv.append("")
    filename = sys.argv[1]
    if not os.path.isfile(filename):
        raise SystemExit(filename + " does not exists")
    elif not os.access(filename, os.R_OK):
        raise SystemExit(filename + " is not accessible")
    else:
        print(filename + " is accessible")

if __name__ == "__main__":
    main()

sys.stdin

import sys
for line in sys.stdin:
    print(line, end="")

def get_content():
    return sys.stdin.readlines()

fileinput

fileinput会遍历sys.argv[1:]列表,并按行依次读取列表中的文件。如果该列表为空,则fileinput默认读取标准输入中的内容。

import fileinput

for line in fileinput.input():
    meta = [
        fileinput.filename(),
        fileinput.fileno(),
        fileinput.filelineno(),
        fileinput.isfirstline(),
        fileinput.isstdin()
    ]
    print(*meta, end="")
    print(line, end="")

getpass

import getpass

user = getpass.getuser()
passwd = getpass.getpass("please input your password:")
print(user, passwd)

configparser

import configparser
cf = configparser.ConfigParser(allow_no_value=True)
cf.read("my.cnf")
cf.sections()
cf.has_section("client")
cf.options("client")
cf.has_option("client", "user")
cf.get("client", "host")
cf.getint("client", "port")
cf.remove_section("client")
cf.add_section("mysql")
cf.set("mysql", "host", "127.0.0.1")
cf.write(open("my_copy.cnf", "w"))

argparser

import argparse

def _argparse():
    parser = argparse.ArgumentParser(description="This is description")
    parser.add_argument("-h", "--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 a switch to true")
    return parser.parse_args()

def main():
    parser = _argparse()
    print(parser)
    print("host =", parser.server)
    print("boolean_switch=", parser.boolean_switch)

if __name__ == "__main__":
    main()

logging

import logging

logging.basicConfig(filename="app.log",
                    level=logging.INFO,
                    format="%(asctime)s : %(levelname)s : %(message)s")

logging.debug("debug message")
logging.info("info message")
logging.warn("warn message")
logging.error("error message")
logging.critical("critical message")

prompt_toolkit

from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

while True:
    user_input = prompt(">",
                        history=FileHistory("history.txt"),
                        auto_suggest=AutoSuggestFromHistory())
    print(user_input)