diff --git a/python fire使用.md b/python fire使用.md new file mode 100644 index 0000000..aaf29e6 --- /dev/null +++ b/python fire使用.md @@ -0,0 +1,65 @@ +## 使用Fire最简单的方法是在任何Python程序结束时调用fire.Fire()。 这会将程序的全部内容暴露给命令行。 +import fire +def hello(name): + return 'Hello {name}!'.format(name=name) +if __name__ == '__main__': + fire.Fire() +从命令行运行程序: +$ python example.py hello World +Hello World! + +## 暴露多个命令最简单的方法是编写多个函数,然后调用Fire。 + +import fire + +def add(x, y): + return x + y + +def multiply(x, y): + return x * y + +if __name__ == '__main__': + fire.Fire() +我们可以这样使用它: +$ python example.py add 10 20 +30 +$ python example.py multiply 10 20 +200 + +## 下面是一个如何使用分组命令创建命令行界面的示例。 + +class IngestionStage(object): + + def run(self): + return 'Ingesting! Nom nom nom...' + +class DigestionStage(object): + + def run(self, volume=1): + return ' '.join(['Burp!'] * volume) + + def status(self): + return 'Satiated.' + +class Pipeline(object): + + def __init__(self): + self.ingestion = IngestionStage() + self.digestion = DigestionStage() + + def run(self): + self.ingestion.run() + self.digestion.run() + +if __name__ == '__main__': + fire.Fire(Pipeline) +以下是使用方式: +$ python example.py run +Ingesting! Nom nom nom... +Burp! +$ python example.py ingestion run +Ingesting! Nom nom nom... +$ python example.py digestion run +Burp! +$ python example.py digestion status +Satiated. \ No newline at end of file