I'm using the click package for creating a command line tool. However, I would like to have a 'list' command. For example:
#click.command
#click.option(help='list...')
def list():
# do stuff here
Is there another way in click to pass in a command name other than having it as the function name? I don't want this function to shadow python's built in list. I've looked through the documentation and can't really find anything about command names -- I've read up on command aliases but that doesn't seem to help this problem. Or do I not need to worry about list being shadowed since it's being wrapped by the click decorator? Thanks in advance.
You can provide the name argument when you use the command decorator. Once you've done that, you can name your function whatever you want:
#click.command(name='list')
def list_command():
pass
See the Click documentation for details.
Related
I have a Click app called "DC" starting with click.Group cli(), which has many subcommands. I'm trying to produce a text file with a list of all commands, arguments, options, and help text as a convenient reference. How do I introspect a Click application?
I experimented using the API reference, but it's confusing. Some of Command's methods (like get_usage()) require a "context" object as the first arg, and I only know two ways to get one:
Be inside a command with #pass_context decorator. (Not always the case.)
Call click.get_current_context() to get the "current" context, which seems to be the one attached to the bottom-level command that is currently being executed.
That seemed to work:
from dc.__main__ import cli
current_ctx = click.get_current_context()
click.echo(cli.get_usage(current_ctx))
This prints the docstring from the cli() function. However, if I try to inspect the list of subcommands:
click.echo(cli.commands)
I get an empty dict. After more exploring, I finally managed to find my way to the real data by doing this:
current_ctx.find_root().command.commands
which returned a dict with all the top-level commands I expected to see.
Is that the preferred method?
In python suppose to find the help of the specific function we use help(function-name) but how to find the same for the .built in function in python such as help(.builtin-function name) but in the command terminal it throws error stating the respective keyword is not found? Thanks in advance and sorry for the language(not comparatively lucid)
I don't get the really correct answer, but here is a link with all the built-in functions sorted in alphabetic order : https://docs.python.org/3/library/functions.html
Enjoy !
What you are trying to do is access the documentation of a method, e.g. help(str.strip). You must provide the name of the method together with the class name (str in this case).
From here:
The built-in function help() invokes the online help system in the
interactive interpreter, which uses pydoc to generate its
documentation as text on the console.
And
For modules, classes, functions and methods, the displayed
documentation is derived from the docstring (i.e. the __doc__
attribute) of the object, and recursively of its documentable members.
So, you can simply access __doc__ attribute of the functions. For example,
print(help.__doc__)
Define the builtin 'help'.
This is a wrapper around pydoc.help that provides a helpful message
when 'help' is typed at the Python interactive prompt.
Calling help() at the Python prompt starts an interactive help
session. Calling help(thing) prints help for the python object
'thing'.
This works with any built-in functions or methods.
I have this chunk of code:
import click
#click.option('--delete_thing', help="Delete some things columns.", default=False)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
I would like to rename the option variable in --delete-thing. But python does not allow dashes in variable names. Is there a way to write this kind of code?
import click
#click.option('--delete-thing', help="Delete some things columns.", default=False, store_variable=delete_thing)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
So delete_thing will be set to the value of delete-thing
By default, click will intelligently map intra-option commandline hyphens to underscores so your code should work as-is. This is used in the click documentation, e.g., in the Choice example. If --delete-thing is intended to be a boolean option, you may also want to make it a boolean argument.
As gbe's answer says, click will automatically convert - in the cli parameters to _ for the python function parameters.
But you can also explicitly name the python variable to whatever you want. In this example, it converts --delete-thing to new_var_name:
import click
#click.command()
#click.option('--delete-thing', 'new_var_name')
def cmd_do_this(new_var_name):
print(f"I deleted the thing: {new_var_name}")
I am using Python's dir() function to determine what attributes and methods a class has.
For example to determine the methods in wx.Frame, I use dir(wx.Frame)
Is there any command to determine the list of arguments for each method? For example, if I want to know what arguments belong to wx.Frame.CreateToolBar().
As mentioned in the comments, you can use help(fun) to enter the help editor with the function's signature and docstring. You can also simply use print fun.__doc__ and for most mature libraries you should get reasonable documentation about the parameters and the function signature.
If you're talking about interactive help, consider using IPython which has some useful extras. For instance you could type %psource fun to get a printout of the source code for the function fun, and with tab completion you could just type wx.Frame. and then hit TAB to see a list of all of the methods and attributes available within wx.Frame.
Even though GP89 seems to have already answered this question, I thought I'd jump in with a little more detail.
First, GP89's suggestion was the use Python's built-in help() method. This is a method you can use in the interactive console. For methods, it will print the method's declaration line along with the class' docstring, if it is defined. You can also access this with <object>.__doc__ For example:
>>> def testHelp(arg1, arg2=0):
... """This is the docstring that will print when you
... call help(testHelp). testHelp.__doc__ will also
... return this string. Here is where you should
... describe your method and all its arguments."""
...
>>> help(testHelp)
Help on function testHelp in module __main__:
testHelp(arg1, arg2=0)
This is the docstring that will print when you
call help(testHelp). testHelp.__doc__ will also
return this string. Here is where you should
describe your method and all its arguments.
>>>
However, another extremely important tool for understanding methods, classes and functions is the toolkit's API. For built-in Python functions, you should check the Python Doc Library. That's where I found the documentation for the help() function. You're using wxPython, whose API can be found here, so a quick search for "wx.Frame api" and you can find this page describing all of wx.Frame's methods and variables. Unfortunately, CreatteToolBar() isn't particularly well documented but you can still see it's arguments:
CreateToolBar(self, style, winid, name)
Happy coding!
When I'm using a 3rd party l
ibrary such as boto, PyCharm seems to be able to auto-complete quite nicely
However, as soon as I define a function of my own, auto-complete breaks down inside that function. I understand why, since I can't give the function any type information about its arguments, so it can't guess how to auto-complete. Is there a way around this issue?
Edit
I tried using the docstring (for Python 2), but still no auto-complete
def delete_oldest_backups(conn, backups_to_keep, backup_description):
"""
delete_oldest_backups(EC2Connection, int, string)
"""
(Also tried boto.ec2.connection.EC2Connection instead of just EC2Connection)
You can use type hints: http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html
def some_method(self, conn):
"""
#type conn: EC2Connection
"""
conn.<autocomplete>
You can specify the type information about the parameters of the function using Python 3 parameter and return value annotations. If you're using Python 2, you can also specify information in the function's docstring. PyCharm understands the format used by docstrings of binary modules in the standard library, for example:
"""
foo(int, string) -> list
Returns the list of something
"""
In order for PyCharm to recognize an instance of an object and retrieve all its methods, we have to use the following statements. But I think that both is a terrible way of wasting programming and run time.
assert isinstance(instanceX, ClassOfInstanceX)
instanceX.{#list of method/properties appears}
Alternatively, you can also use the class name will recall the method or property everytime you want to invoke it and pass in the instance to the self parameter. But this is too verbose, for my liking, esp for nested class
ClassOfInstanceX.{#list of method/properties appears}
# then you will have...
ClassOfInstance.method(instanceX, args...)
You can install the library via pyCharm "package manager".
Go to Settings -> Project Interpreter -> Python Interpreters
And in the Packages list, click on install and search for the library you want to install
Once installed, auto-complete will be available on editor.
Hope this is what you are looking for.