我的编程空间,编程开发者的网络收藏夹
学习永远不晚

python-fire的使用

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

python-fire的使用

本文完全转载自:https://github.com/google/python-fire/blob/master/docs/guide.md

fire简单参考实例:http://blog.csdn.net/u010099080/article/details/70332074


The Python Fire Guide

Introduction

Welcome to the Python Fire guide! Python Fire is a Python library that will turnany Python component into a command line interface with just a single call toFire.

Let's get started!

Installation

To install Python Fire from pypi, run:

pip install fire

Alternatively, to install Python Fire from source, clone the source and run:

python setup.py install

Hello World

Version 1: fire.Fire()

The easiest way to use Fire is to take any Python program, and then simply callfire.Fire() at the end of the program. This will expose the full contents ofthe program to the command line.

import fire

def hello(name):
  return 'Hello {name}!'.format(name=name)

if __name__ == '__main__':
  fire.Fire()

Here's how we can run our program from the command line:

$ python example.py hello World
Hello World!
Version 2: fire.Fire(<fn>)

Let's modify our program slightly to only expose the hello function to thecommand line.

import fire

def hello(name):
  return 'Hello {name}!'.format(name=name)

if __name__ == '__main__':
  fire.Fire(hello)

Here's how we can run this from the command line:

$ python example.py World
Hello World!

Notice we no longer have to specify to run the hello function, because wecalled fire.Fire(hello).

Version 3: Using a main

We can alternatively write this program like this:

import fire

def hello(name):
  return 'Hello {name}!'.format(name=name)

def main():
  fire.Fire(hello)

if __name__ == '__main__':
  main()

Or if we're usingentry points,then simply this:

import fire

def hello(name):
  return 'Hello {name}!'.format(name=name)

def main():
  fire.Fire(hello)

Exposing Multiple Commands

In the previous example, we exposed a single function to the command line. Nowwe'll look at ways of exposing multiple functions to the command line.

Version 1: fire.Fire()

The simplest way to expose multiple commands is to write multiple functions, andthen call Fire.

import fire

def add(x, y):
  return x + y

def multiply(x, y):
  return x * y

if __name__ == '__main__':
  fire.Fire()

We can use this like so:

$ python example.py add 10 20
30
$ python example.py multiply 10 20
200

You'll notice that Fire correctly parsed 10 and 20 as numbers, rather thanas strings. Read more about argument parsing here.

Version 2: fire.Fire(<dict>)

In version 1 we exposed all the program's functionality to the command line. Byusing a dict, we can selectively expose functions to the command line.

import fire

def add(x, y):
  return x + y

def multiply(x, y):
  return x * y

if __name__ == '__main__':
  fire.Fire({
      'add': add,
      'multiply': multiply,
  })

We can use this in the same way as before:

$ python example.py add 10 20
30
$ python example.py multiply 10 20
200
Version 3: fire.Fire(<object>)

Fire also works on objects, as in this variant. This is a good way to exposemultiple commands.

import fire

class Calculator(object):

  def add(self, x, y):
    return x + y

  def multiply(self, x, y):
    return x * y

if __name__ == '__main__':
  calculator = Calculator()
  fire.Fire(calculator)

We can use this in the same way as before:

$ python example.py add 10 20
30
$ python example.py multiply 10 20
200
Version 4: fire.Fire(<class>)

Fire also works on classes. This is another good way to expose multiplecommands.

import fire

class Calculator(object):

  def add(self, x, y):
    return x + y

  def multiply(self, x, y):
    return x * y

if __name__ == '__main__':
  fire.Fire(Calculator)

We can use this in the same way as before:

$ python example.py add 10 20
30
$ python example.py multiply 10 20
200

Why might you prefer a class over an object? One reason is that you can passarguments for constructing the class too, as in this broken calculator example.

import fire

class BrokenCalculator(object):

  def __init__(self, offset=1):
      self._offset = offset

  def add(self, x, y):
    return x + y + self._offset

  def multiply(self, x, y):
    return x * y + self._offset

if __name__ == '__main__':
  fire.Fire(BrokenCalculator)

When you use a broken calculator, you get wrong answers:

$ python example.py add 10 20
31
$ python example.py multiply 10 20
201

But you can always fix it:

$ python example.py add 10 20 --offset=0
30
$ python example.py multiply 10 20 --offset=0
200

Unlike calling ordinary functions, which can be done both with positionalarguments and named arguments (--flag syntax), arguments to __init__functions must be passed with the --flag syntax. See the section oncalling functions for more.

Grouping Commands

Here's an example of how you might make a command line interface with groupedcommands.

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)

Here's how this looks at the command line:

$ 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.

You can nest your commands in arbitrarily complex ways, if you're feeling grumpyor adventurous.

Accessing Properties

In the examples we've looked at so far, our invocations of python example.pyhave all run some function from the example program. In this example, we simplyaccess a property.

from airports import airports

import fire

class Airport(object):

  def __init__(self, code):
    self.code = code
    self.name = dict(airports).get(self.code)
    self.city = self.name.split(',')[0] if self.name else None

if __name__ == '__main__':
  fire.Fire(Airport)

Now we can use this program to learn about airport codes!

$ python example.py --code=JFK code
JFK
$ python example.py --code=SJC name
San Jose-Sunnyvale-Santa Clara, CA - Norman Y. Mineta San Jose International (SJC)
$ python example.py --code=ALB city
Albany-Schenectady-Troy

By the way, you can find thisairports module here.

Chaining Function Calls

When you run a Fire CLI, you can take all the same actions on the result ofthe call to Fire that you can take on the original object passed in.

For example, we can use our Airport CLI from the previous example like this:

$ python example.py --code=ALB city upper
ALBANY-SCHENECTADY-TROY

This works since upper is a method on all strings.

So, if you want to set up your functions to chain nicely, all you have to do ishave a class whose methods return self. Here's an example.

import fire

class BinaryCanvas(object):
  """A canvas with which to make binary art, one bit at a time."""

  def __init__(self, size=10):
    self.pixels = [[0] * size for _ in range(size)]
    self._size = size
    self._row = 0  # The row of the cursor.
    self._col = 0  # The column of the cursor.

  def __str__(self):
    return '\n'.join(' '.join(str(pixel) for pixel in row) for row in self.pixels)

  def show(self):
    print(self)
    return self

  def move(self, row, col):
    self._row = row % self._size
    self._col = col % self._size
    return self

  def on(self):
    return self.set(1)

  def off(self):
    return self.set(0)

  def set(self, value):
    self.pixels[self._row][self._col] = value
    return self

if __name__ == '__main__':
  fire.Fire(BinaryCanvas)

Now we can draw stuff :).

$ python example.py move 3 3 on move 3 6 on move 6 3 on move 6 6 on move 7 4 on move 7 5 on __str__
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

It's supposed to be a smiley face.

Can we make an even simpler example than Hello World?

Yes, this program is even simpler than our original Hello World example.

import fire
english = 'Hello World'
spanish = 'Hola Mundo'
fire.Fire()

You can use it like this:

$ python example.py english
Hello World
$ python example.py spanish
Hola Mundo

Calling Functions

Arguments to a constructor are passed by name using flag syntax --name=value.

For example, consider this simple class:

import fire

class Building(object):

  def __init__(self, name, stories=1):
    self.name = name
    self.stories = 1

  def climb_stairs(self, stairs_per_story=10):
    for story in range(self.stories):
      for stair in range(1, stairs_per_story):
        yield stair
        yield 'Phew!'
    yield 'Done!'

if __name__ == '__main__':
  fire.Fire(Building)

We can instantiate it as follows: python example.py --name="Sherrerd Hall"

Arguments to other functions may be passed positionally or by name using flagsyntax.

To instantiate a Building and then run the climb_stairs function, thefollowing commands are all valid:

$ python example.py --name="Sherrerd Hall" --stories=3 climb_stairs 10
$ python example.py --name="Sherrerd Hall" climb_stairs --stairs_per_story=10
$ python example.py --name="Sherrerd Hall" climb_stairs --stairs-per-story 10
$ python example.py climb-stairs --stairs-per-story 10 --name="Sherrerd Hall"

You'll notice that hyphens and underscores (- and _) are interchangeable inmember names and flag names.

You'll also notice that the constructor's arguments can come after thefunction's arguments or before the function.

You'll also notice that the equal sign between the flag name and its value isoptional.

Functions with *varargs and **kwargs

Fire supports functions that take *varargs or **kwargs. Here's an example:

import fire

def order_by_length(*items):
  """Orders items by length, breaking ties alphabetically."""
  sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item)))
  return ' '.join(sorted_items)

if __name__ == '__main__':
  fire.Fire(order_by_length)

To use it, we run:

$ python example.py dog cat elephant
cat dog elephant

You can use a separator to indicate that you're done providing arguments to afunction. All arguments after the separator will be used to process the resultof the function, rather than being passed to the function itself. The defaultseparator is the hyphen -.

Here's an example where we use a separator.

$ python example.py dog cat elephant - upper
CAT DOG ELEPHANT

Without the separator, upper would have been treated as another argument.

$ python example.py dog cat elephant upper
cat dog upper elephant

You can change the separator with the --separator flag. Flags are alwaysseparated from your Fire command by an isolated --. Here's an example where wechange the separator.

$ python example.py dog cat elephant X upper -- --separator=X
CAT DOG ELEPHANT

Separators can be useful when a function accepts *varargs, **kwargs, ordefault values that you don't want to specify. It is also important to rememberto change the separator if you want to pass - as an argument.

Argument Parsing

The types of the arguments are determined by their values, rather than by thefunction signature where they're used. You can pass any Python literal from thecommand line: numbers, strings, tuples, lists, dictionaries, (sets are onlysupported in some versions of Python). You can also nest the collectionsarbitrarily as long as they only contain literals.

To demonstrate this, we'll make a small example program that tells us the typeof any argument we give it:

import fire
fire.Fire(lambda obj: type(obj).__name__)

And we'll use it like so:

$ python example.py 10
int
$ python example.py 10.0
float
$ python example.py hello
str
$ python example.py '(1,2)'
tuple
$ python example.py [1,2]
list
$ python example.py True
bool
$ python example.py {name: David}
dict

You'll notice in that last example that bare-words are automatically replacedwith strings.

Be careful with your quotes! If you want to pass the string "10", rather thanthe int 10, you'll need to either escape or quote your quotes. Otherwise Bashwill eat your quotes and pass an unquoted 10 to your Python program, whereFire will interpret it as a number.

$ python example.py 10
int
$ python example.py "10"
int
$ python example.py '"10"'
str
$ python example.py "'10'"
str
$ python example.py \"10\"
str

Be careful with your quotes! Remember that Bash processes your arguments first,and then Fire parses the result of that.If you wanted to pass the dict {"name": "David Bieber"} to your program, youmight try this:

$ python example.py '{"name": "David Bieber"}'  # Good! Do this.
dict
$ python example.py {"name":'"David Bieber"'}  # Okay.
dict
$ python example.py {"name":"David Bieber"}  # Wrong. This is parsed as a string.
str
$ python example.py {"name": "David Bieber"}  # Wrong. This isn't even treated as a single argument.
<error>
$ python example.py '{"name": "Justin Bieber"}'  # Wrong. This is not the Bieber you're looking for. (The syntax is fine though :))
dict
Boolean Arguments

The tokens True and False are parsed as boolean values.

You may also specify booleans via flag syntax --name and --noname, which setname to True and False respectively.

Continuing the previous example, we could run any of the following:

$ python example.py --obj=True
bool
$ python example.py --obj=False
bool
$ python example.py --obj
bool
$ python example.py --noobj
bool

Be careful with boolean flags! If a token other than another flag immediatelyfollows a flag that's supposed to be a boolean, the flag will take on the valueof the token rather than the boolean value. You can resolve this: by putting aseparator after your last flag, by explicitly stating the value of the booleanflag (as in --obj=True), or by making sure there's another flag after anyboolean flag argument.

Using Fire Flags

Fire CLIs all come with a number of flags. These flags should be separated fromthe Fire command by an isolated --. If there is at least one isolated --argument, then arguments after the final isolated -- are treated as flags,whereas all arguments before the final isolated -- are considered part of theFire command.

One useful flag is the --interactive flag. Use the --interactive flag on anyCLI to enter a Python REPL with all the modules and variables used in thecontext where Fire was called already available to you for use. Other usefulvariables, such as the result of the Fire command will also be available. Usethis feature like this: python example.py -- --interactive.

You can add the help flag to any command to see help and usage information. Fireincorporates your docstrings into the help and usage information that itgenerates. Fire will try to provide help even if you omit the isolated --separating the flags from the Fire command, but may not always be able to, sincehelp is a valid argument name. Use this feature like this:python example.py -- --help.

The complete set of flags available is shown below, in the reference section.

Reference

Setup Command Notes
install pip install fire  
Creating a CLI
Creating a CLI Command Notes
import import fire  
Call fire.Fire() Turns the current module into a Fire CLI.
Call fire.Fire(component) Turns component into a Fire CLI.
Flags
Using a CLI Command Notes
Help command -- --help Show help and usage information for the command.
REPL command -- --interactive Enter interactive mode.
Separator command -- --separator=X This sets the separator to X. The default separator is -.
Completion command -- --completion Generate a completion script for the CLI.
Trace command -- --trace Gets a Fire trace for the command.
Verbose command -- --verbose Include private members in the output.

Note that flags are separated from the Fire command by an isolated -- arg.

Disclaimer

Python Fire is not an official Google product.

python-fire的使用

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

python-fire的使用

本文完全转载自:https://github.com/google/python-fire/blob/master/docs/guide.md#version-3-firefireobjectfire简单参考实例:http://blog.c
2023-01-31

怎么使用Python命令行库fire

本篇内容主要讲解“怎么使用Python命令行库fire”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用Python命令行库fire”吧!一、前言今天要介绍的 fire则是用一种面向广义对象
2023-06-16

python中 fire的作用是什么

这期内容当中小编将会给大家带来有关python中 fire的作用是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。python是什么意思Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的
2023-06-14

python fire怎么在函数和类中应用

小编给大家分享一下python fire怎么在函数和类中应用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!python是什么意思Python是一种跨平台的、具有解
2023-06-14

python+etcd的使用

python-etcd是一个etcd的python客户端,它的安装方法如下:git clone https://github.com/jplana/python-etcd.gitcd python-etcdpython setup.py i
2023-01-31

Python collection的使用

Python中的基本数据结构有list,dict,tuple,set。Python还有一个功能比较强大的包collections,可以处理并维护一个有序的dict,可以提高程序的运行效率。 1、collections中defaultdict
2023-01-31

Python中的*使用

Python中的*使用  在为函数传递参数和函数定义时使用参数的时候,时常会看到有和 *和**,下面分别讲解其作用。调用函数时使用*和 ** 假设有函数 def test(a, b, c)test(*args):* 的作用其实就是把序列 a
2023-01-31

thrift的使用--python

转载blog:http://www.cnblogs.com/pinking/p/7726478.html在这里要补充一点的就是在在这里python要安装thrift包时候,可以直接在安装好的thrift好的模块中sudo python se
2023-01-31

使用 Python 的 jsonsche

在OpenStack中, 使用了Python的 jsonschema包, 对json字符串做了验证.Python JSON Schema Libraryhttps://pypi.python.org/pypi/jsonschemaJSON
2023-01-31

pygrametl的使用--python

pygrametl是一个python的package用于ETL(Extract-Transform-Load )简例import MySQLdbfrom pygrametl.datasources import SQLSourceconn
2023-01-31

python的tkinter使用

__author__ = 'Python'import tkinter as tkclass Application(tk.Frame):    def __init__(self, master=None):        tk.Fram
2023-01-31

python下的MySQLdb使用

下载安装MySQLdb <1>linux版本http://sourceforge.net/projects/mysql-python/ 下载,在安装是要先安装setuptools,然后在下载文件目录下,修改mysite.cfg,指定本地my
2023-01-31

python中list的使用

1、list(列表)是一种有序的集合,可以随时添加、修改、删除其中的元素。举例:listClassName = ['Jack','Tom','Mark']                    列表可以根据索引获取元素,如:listClas
2023-01-30

python中assert的使用

在python程序中,如果想要确保程序中的某个条件一定为真才会继续执行的话,而可以使用assert来实现。  例如:>>> age = 10>>> assert 0>> assert age>20Traceback (mos
2023-01-31

Python中ghost的使用

ghost.py is a webkit web client written in python.from ghost import Ghostghost = Ghost()page, extra_resources = ghost.op
2023-01-31

peewee的使用 python orm

自动提交,和定义 table name 。 爬虫。 -- 自动判断 返回的编码resp.encoding = resp.apparent_encoding爬虫- http协议。 http://yxtsunny.lofter.com/po
2023-01-31

python sqlite3 的使用,性

sqlite3 的使用,性能及限制python 中使用sqlite3首先是基本的使用:# coding=utf8__author__ = 'Administrator'# 导入模块,在 python 中是已经内置了这个模块,所以就不需要安装
2023-01-31

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录