Python Kindle Fire

Source: Internet
Author: User

One: Instruction
Python fire was a python library that would turn any Python component to a command line interface with just a single call to the fire.
Two: Installation
To install the Python fire from PyPI, run:
Pip Install fire

Hello World

Version 1:fire. Fire ()

The easiest-on-the-use-fire-is-take-any-Python program, and then simply-call fire. Fire () in the end of the program. This would expose the full contents of the program to the command line.

Import Kindle 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 ( )

Let's modify our program slightly to only expose the "Hello function to" command line.

Import Kindle 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 has to specify to run the Hello function and because we called fire. Fire (Hello).

Version 3:using a Main

We can alternatively write this program like this:

Import Kindle Fire

def hello (name):
Return ' Hello {name}! '. Format (name=name)

def main ():
Fire. Fire (Hello)

If name = = 'main':
Main ()
Or if we ' re using entry points, then simply this:

Import Kindle 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. Now we'll look at ways of exposing multiple functions to the command line.

Version 1:fire. Fire ()

The simplest-expose multiple commands is-write multiple functions, and then call fire.

Import Kindle Fire

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

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

If name = = 'main':
Fire. Fire ()
We can use this as so:

$ python example.py add 10 20
30
$ python example.py Multiply 10 20
200
You'll notice that fire correctly parsed and as numbers, rather than as strings. Read more on argument parsing here.

Version 2:fire. Fire ( )

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

Import Kindle 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 the same-a-before:

$ python example.py add 10 20
30
$ python example.py Multiply 10 20
200
Version 3:fire. Fire ()

Fire also works on objects, as in the this variant. This is a good the expose multiple commands.

Import Kindle 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 the same-a-before:

$ python example.py add 10 20
30
$ python example.py Multiply 10 20
200
Version 4:fire. Fire ( )

Fire also works on classes. This is another good the expose multiple commands.

Import Kindle 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 the same-a-before:

$ python example.py add 10 20
30
$ python example.py Multiply 10 20
200
Why might your prefer a class over an object? One reason is so can pass arguments for constructing the class too, as in this broken calculator example.

Import Kindle 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 your use of 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 ten--offset=0
30
$ python example.py Multiply--offset=0
200
Unlike calling ordinary functions, which can be do both with positional arguments and named arguments (--flag syntax), a Rguments to init functions must is passed with the--flag syntax. See the sections on calling functions for more.

Grouping Commands

Here's an example on how to might make a command line interface with grouped commands.

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 grumpy or adventurous.

accessing Properties

In the examples we ' ve looked @ so far, our invocations of Python example.py has all run some function from the example p Rogram. In this example, we simply access a property.

From Airports Import airports

Import Kindle 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 the-the-the-can find this airports module here.

Chaining Function Calls

When you run a fire CLI, you can take all the same actions on the result of the "the call" to the fire so you can take the orig Inal 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 are a method on all strings.

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

Import Kindle 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 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 being a smiley face.

Can we make a even simpler example than Hello world?

Yes, this program is even simpler than we original Hello world example.

Import Kindle Fire
中文版 = ' Hello world '
spanish = ' Hola Mundo '
Fire. Fire ()
You can use it as this:

$ python example.py 中文版
Hello World
$ python example.py Spanish
Hola Mundo
Calling Functions

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

For example, consider this simple class:

Import Kindle 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 stories 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 and functions May is passed positionally or by name using flag syntax.

To instantiate a Building and then run the Climb_stairs function, the following commands is 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--name= "Sherrerd Hall"
You'll notice that hyphens and underscores (-and _) is interchangeable in member names and flag names.

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

You'll also notice the equal sign between the flag name and its value is optional.

Functions with *varargs and **kwargs

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

Import Kindle 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 this you ' re do providing arguments to a function. All arguments after the separator would be used to process the result of the function, rather than being passed to the Func tion itself. The default separator is the hyphen-.

Here's a example where we use a separator.

$ python example.py dog cat Elephant-upper
CAT DOG ELEPHANT
Without the separator, upper would has 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 is always separated from your fire command by an isolated--. Here's a example where we change the separator.

$ python example.py dog cat Elephant X Upper----separator=x
CAT DOG ELEPHANT
Separators can useful when a function is accepts *varargs, **kwargs, or default values that you don ' t want to specify. It is also important to remember to change the separator if you want to pass-as an argument.

Argument parsing

The types of the arguments is determined by their values, rather than by the function signature where they ' re used. Can pass any Python literal from the command line:numbers, strings, tuples, lists, dictionaries, (sets is only Suppo RTed in some versions of Python). You can also nest the collections arbitrarily as a long as they only contain literals.

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

Import Kindle 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 '
Tuple
$ Python example.py [up]
List
$ python example.py True
bool
$ python example.py {name:david}
Dict
You'll notice in the last example that Bare-words is automatically replaced with strings.

Be careful with your quotes! If you want to pass the string "Ten", rather than the int, you'll need to either escape or quote your quotes. Otherwise Bash would eat your quotes and pass an unquoted to your Python program, where fire would interpret it as a numb Er.

$ 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 the. If you wanted to pass the dict {"name": "David Bieber"} to your program, you might 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.

$ python example.py ' {"name": "Justin Bieber"} ' # wrong. This isn't the Bieber you ' re looking for. (The syntax is fine though:))
Dict
Boolean Arguments

The tokens True and False are parsed as Boolean values.

Also specify Booleans via flag syntax--name and--noname, which set name 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 immediately follows a flag this ' s supposed to be a Boolean, the flag would take the V Alue of the token rather than the Boolean value. You can resolve this:by putting a separator after your last flag, by explicitly stating the value of the Boolean flag (as In--obj=true), or by making sure there's another flag after any Boolean flag argument.

Using Fire Flags

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

One useful flag is the--interactive flag. Use the--INTERACTIVE flag on any CLI to enter a Python REPL with all the modules and variables used in the context where Fire is called already available to. Other useful variables, such as the result of the fire command would also be available. Use the feature like This:python example.py----Interactive.

You can add the "Help flag" to the "any command" to "see" and "usage information." Fire incorporates your docstrings to the and usage information that it generates. Fire would try to provide help even if you omit the isolated--separating the "The flags from the" Fire command, and may not alw Ays be able to, since help is a valid argument name. Use the feature like This:python example.py----Help.

The complete set of flags available are 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 to a fire CLI.
Call fire. Fire (component) Turns component to 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 is separated from the fire command by an isolated-arg.

https://google.github.io/python-fire/guide/#can-we-make-an-even-simpler-example-than-hello-world

Python Kindle Fire

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.