Command-Line Pyramid¶
Your Pyramid application can be controlled and inspected using a variety of command-line utilities. These utilities are documented in this chapter.
We commonly refer to this collection of utilities as "p-scripts", which is short for "Pyramid console scripts".
Each p-script's command line usage details is available in the p* Scripts Documentation.
Running p-scripts¶
All of the Pyramid console scripts may be run either:
by its name
as a Python module
Running by p*
script name¶
Each of Pyramid's console scripts may be run by its name. For example:
$VENV/bin/pserve development.ini --reload
Note
$VENV/bin/
is a convention we use to simplify Pyramid documentation.
It represents the bin
directory in a virtual environment, where $VENV
is an environment variable representing its path.
See Installing Pyramid on a Unix System and Why use $VENV/bin/pip instead of source bin/activate, then pip for more information.
Using Custom Arguments to Python when Running p*
Scripts¶
Added in version 1.5.
Each of Pyramid's console scripts (pserve
, pviews
, etc.) can be run
using python3 -m
, allowing custom arguments to be sent to the
Python interpreter at runtime. For example:
python3 -m pyramid.scripts.pserve development.ini --reload
pviews
: Displaying Matching Views for a Given URL¶
See also
See also the output of pviews --help.
For a big application with several views, it can be hard to keep the view
configuration details in your head, even if you defined all the views yourself.
You can use the pviews
command in a terminal window to print a summary of
matching routes and views for a given URL in your application. The pviews
command accepts two arguments. The first argument to pviews
is the path to
your application's .ini
file and section name inside the .ini
file
which points to your application. This should be of the format
config_file#section_name
. The second argument is the URL to test for
matching views. The section_name
may be omitted; if it is, it's considered
to be main
.
Here is an example for a simple view configuration using traversal:
1$VENV/bin/pviews development.ini#tutorial /FrontPage
2
3URL = /FrontPage
4
5 context: <tutorial.models.Page object at 0xa12536c>
6 view name:
7
8 View:
9 -----
10 tutorial.views.view_page
11 required permission = view
The output always has the requested URL at the top and below that all the views that matched with their view configuration details. In this example only one view matches, so there is just a single View section. For each matching view, the full code path to the associated view callable is shown, along with any permissions and predicates that are part of that view configuration.
A more complex configuration might generate something like this:
1$VENV/bin/pviews development.ini#shootout /about
2
3URL = /about
4
5 context: <shootout.models.RootFactory object at 0xa56668c>
6 view name: about
7
8 Route:
9 ------
10 route name: about
11 route pattern: /about
12 route path: /about
13 subpath:
14 route predicates (request method = GET)
15
16 View:
17 -----
18 shootout.views.about_view
19 required permission = view
20 view predicates (request_param testing, header X/header)
21
22 Route:
23 ------
24 route name: about_post
25 route pattern: /about
26 route path: /about
27 subpath:
28 route predicates (request method = POST)
29
30 View:
31 -----
32 shootout.views.about_view_post
33 required permission = view
34 view predicates (request_param test)
35
36 View:
37 -----
38 shootout.views.about_view_post2
39 required permission = view
40 view predicates (request_param test2)
In this case, we are dealing with a URL dispatch application. This specific URL has two matching routes. The matching route information is displayed first, followed by any views that are associated with that route. As you can see from the second matching route output, a route can be associated with more than one view.
For a URL that doesn't match any views, pviews
will simply print out a Not
found message.
pshell
: The Interactive Shell¶
See also
See also the output of pshell --help.
Once you've installed your program for development using pip install -e .
,
you can use an interactive Python shell to execute expressions in a Python
environment exactly like the one that will be used when your application runs
"for real". To do so, use the pshell
command line utility.
The argument to pshell
follows the format config_file#section_name
where config_file
is the path to your application's .ini
file and
section_name
is the app
section name inside the .ini
file which
points to your application. For example, your application .ini
file might
have an [app:main]
section that looks like so:
1[app:main]
2use = egg:MyProject
3pyramid.reload_templates = true
4pyramid.debug_authorization = false
5pyramid.debug_notfound = false
6pyramid.debug_templates = true
7pyramid.default_locale_name = en
If so, you can use the following command to invoke a debug shell using the name
main
as a section name:
$VENV/bin/pshell starter/development.ini#main
Python 2.6.5 (r265:79063, Apr 29 2010, 00:31:32)
[GCC 4.4.3] on linux2
Type "help" for more information.
Environment:
app The WSGI application.
registry Active Pyramid registry.
request Active request object.
root Root of the default resource tree.
root_factory Default root factory used to create `root`.
>>> root
<myproject.resources.MyResource object at 0x445270>
>>> registry
<Registry myproject>
>>> registry.settings['pyramid.debug_notfound']
False
>>> from myproject.views import my_view
>>> from pyramid.request import Request
>>> r = Request.blank('/')
>>> my_view(r)
{'project': 'myproject'}
The WSGI application that is loaded will be available in the shell as the
app
global. Also, if the application that is loaded is the Pyramid
app with no surrounding middleware, the root
object returned by the
default root factory, registry
, and request
will be available.
You can also simply rely on the main
default section name by omitting any
hash after the filename:
$VENV/bin/pshell starter/development.ini
Press Ctrl-D
to exit the interactive shell (or Ctrl-Z
on Windows).
Extending the Shell¶
It is convenient when using the interactive shell often to have some variables
significant to your application already loaded as globals when you start the
pshell
. To facilitate this, pshell
will look for a special [pshell]
section in your .ini
file and expose the subsequent key/value pairs to the
shell. Each key is a variable name that will be global within the pshell
session; each value is a dotted Python name. If specified, the special
key setup
should be a dotted Python name pointing to a callable
that accepts the dictionary of globals that will be loaded into the shell. This
allows for some custom initializing code to be executed each time the
pshell
is run. The setup
callable can also be specified from the
commandline using the --setup
option which will override the key in the .ini
file.
For example, you want to expose your model to the shell along with the database
session so that you can mutate the model on an actual database. Here, we'll
assume your model is stored in the myapp.models
package and that you're
using pyramid_tm
to configure a transaction manager on the request as
request.tm
.
1[pshell]
2setup = myapp.lib.pshell.setup
3models = myapp.models
By defining the setup
callable, we will create the module myapp.lib.pshell
containing a callable named setup
that will receive the global environment before it is exposed to the shell. Here we mutate the environment's request as well as add a new value containing a WebTest version of the application to which we can easily submit requests. The setup
callable can also be a generator which can wrap the entire shell lifecycle, executing code when the shell exits.
1# myapp/lib/pshell.py
2from contextlib import suppress
3from transaction.interfaces import NoTransaction
4from webtest import TestApp
5
6def setup(env):
7 request = env['request']
8 request.host = 'www.example.com'
9 request.scheme = 'https'
10
11 env['testapp'] = TestApp(env['app'])
12
13 # start a transaction which can be used in the shell
14 request.tm.begin()
15
16 # if using the SQLAlchemy backend from our cookiecutter, the dbsession is
17 # connected to the transaction manager above
18 env['tm'] = request.tm
19 env['dbsession'] = request.dbsession
20 try:
21 yield
22
23 finally:
24 with suppress(NoTransaction):
25 request.tm.abort()
When this .ini
file is loaded, the extra variable models
will be available for use immediately. Since a setup
callable was also specified, it is executed and new variables testapp
, tm
, and dbsession
are exposed, and the request is configured to generate URLs from the host http://www.example.com
. For example:
$VENV/bin/pshell starter/development.ini
Python 2.6.5 (r265:79063, Apr 29 2010, 00:31:32)
[GCC 4.4.3] on linux2
Type "help" for more information.
Environment:
app The WSGI application.
registry Active Pyramid registry.
request Active request object.
root Root of the default resource tree.
root_factory Default root factory used to create `root`.
testapp <webtest.TestApp object at ...>
Custom Variables:
dbsession
model myapp.models
tm
>>> testapp.get('/')
<200 OK text/html body='<!DOCTYPE...l>\n'/3337>
>>> request.route_url('home')
'https://www.example.com/'
>>> user = dbsession.query(models.User).get(1)
>>> user.name = 'Joe'
>>> tm.commit()
>>> tm.begin()
>>> user = dbsession.query(models.User).get(1)
>>> user.name == 'Joe'
'Joe'
Alternative Shells¶
The pshell
command can be easily extended with alternate REPLs if the
default python REPL is not satisfactory. Assuming you have a binding
installed such as pyramid_ipython
it will normally be auto-selected and
used. You may also specifically invoke your choice with the -p choice
or
--python-shell choice
option.
$VENV/bin/pshell -p ipython development.ini#MyProject
You may use the --list-shells
option to see the available shells.
$VENV/bin/pshell --list-shells
Available shells:
bpython
ipython
python
If you want to use a shell that isn't supported out of the box, you can
introduce a new shell by registering an entry point in your setup.py
:
setup(
entry_points={
'pyramid.pshell_runner': [
'myshell=my_app:ptpython_shell_factory',
],
},
)
And then your shell factory should return a function that accepts two
arguments, env
and help
, which would look like this:
from ptpython.repl import embed
def ptpython_shell_runner(env, help):
print(help)
return embed(locals=env)
Changed in version 1.6: User-defined shells may be registered using entry points. Prior to this
the only supported shells were ipython
, bpython
and python
.
ipython
and bpython
have been moved into their respective
packages pyramid_ipython
and pyramid_bpython
.
Setting a Default Shell¶
You may use the default_shell
option in your [pshell]
ini section to
specify a list of preferred shells.
1[pshell]
2default_shell = ptpython ipython bpython
Added in version 1.6.
proutes
: Displaying All Application Routes¶
See also
See also the output of proutes --help.
You can use the proutes
command in a terminal window to print a summary of
routes related to your application. Much like the pshell
command (see
pshell: The Interactive Shell), the proutes
command accepts one argument with
the format config_file#section_name
. The config_file
is the path to
your application's .ini
file, and section_name
is the app
section
name inside the .ini
file which points to your application. By default,
the section_name
is main
and can be omitted.
For example:
1$VENV/bin/proutes development.ini
2Name Pattern View Method
3---- ------- ---- ------
4debugtoolbar /_debug_toolbar/*subpath <wsgiapp> *
5__static/ /static/*subpath dummy_starter:static/ *
6__static2/ /static2/*subpath /var/www/static/ *
7__pdt_images/ /pdt_images/*subpath pyramid_debugtoolbar:static/img/ *
8a / <unknown> *
9no_view_attached / <unknown> *
10route_and_view_attached / app1.standard_views.route_and_view_attached *
11method_conflicts /conflicts app1.standard_conflicts <route mismatch>
12multiview /multiview app1.standard_views.multiview GET,PATCH
13not_post /not_post app1.standard_views.multiview !POST,*
proutes
generates a table with four columns: Name, Pattern, View, and
Method. The items listed in the Name column are route names, the items
listed in the Pattern column are route patterns, the items listed in the View
column are representations of the view callable that will be invoked when a
request matches the associated route pattern, and the items listed in the
Method column are the request methods that are associated with the route name.
The View column may show <unknown>
if no associated view callable could be
found. The Method column, for the route name, may show either <route
mismatch>
if the view callable does not accept any of the route's request
methods, or *
if the view callable will accept any of the route's request
methods. If no routes are configured within your application, nothing will be
printed to the console when proutes
is executed.
It is convenient when using the proutes
command often to configure which
columns and the order you would like to view them. To facilitate this,
proutes
will look for a special [proutes]
section in your .ini
file
and use those as defaults.
For example you may remove the request method and place the view first:
1[proutes]
2format = view
3 name
4 pattern
You can also separate the formats with commas or spaces:
1[proutes]
2format = view name pattern
3
4[proutes]
5format = view, name, pattern
If you want to temporarily configure the columns and order, there is the
argument --format
, which is a comma separated list of columns you want to
include. The current available formats are name
, pattern
, view
, and
method
.
ptweens
: Displaying "Tweens"¶
See also
See also the output of ptweens --help.
A tween is a bit of code that sits between the main Pyramid application
request handler and the WSGI application which calls it. A user can get a
representation of both the implicit tween ordering (the ordering specified by
calls to pyramid.config.Configurator.add_tween()
) and the explicit tween
ordering (specified by the pyramid.tweens
configuration setting) using the
ptweens
command. Tween factories will show up represented by their
standard Python dotted name in the ptweens
output.
For example, here's the ptweens
command run against a system configured
without any explicit tweens:
1$VENV/bin/ptweens development.ini
2"pyramid.tweens" config value NOT set (implicitly ordered tweens used)
3
4Implicit Tween Chain
5
6Position Name Alias
7-------- ---- -----
8- - INGRESS
90 pyramid_debugtoolbar.toolbar.toolbar_tween_factory pdbt
101 pyramid.tweens.excview_tween_factory excview
11- - MAIN
Here's the ptweens
command run against a system configured with explicit
tweens defined in its development.ini
file:
1$VENV/bin/ptweens development.ini
2"pyramid.tweens" config value set (explicitly ordered tweens used)
3
4Explicit Tween Chain (used)
5
6Position Name
7-------- ----
8- INGRESS
90 starter.tween_factory2
101 starter.tween_factory1
112 pyramid.tweens.excview_tween_factory
12- MAIN
13
14Implicit Tween Chain (not used)
15
16Position Name
17-------- ----
18- INGRESS
190 pyramid_debugtoolbar.toolbar.toolbar_tween_factory
201 pyramid.tweens.excview_tween_factory
21- MAIN
Here's the application configuration section of the development.ini
used by
the above ptweens
command which reports that the explicit tween chain is
used:
1[app:main]
2use = egg:starter
3reload_templates = true
4debug_authorization = false
5debug_notfound = false
6debug_routematch = false
7debug_templates = true
8default_locale_name = en
9pyramid.include = pyramid_debugtoolbar
10pyramid.tweens = starter.tween_factory2
11 starter.tween_factory1
12 pyramid.tweens.excview_tween_factory
See Registering Tweens for more information about tweens.
prequest
: Invoking a Request¶
See also
See also the output of prequest --help.
You can use the prequest
command-line utility to send a request to your
application and see the response body without starting a server.
There are two required arguments to prequest
:
The config file/section: follows the format
config_file#section_name
, whereconfig_file
is the path to your application's.ini
file andsection_name
is theapp
section name inside the.ini
file. Thesection_name
is optional; it defaults tomain
. For example:development.ini
.The path: this should be the non-URL-quoted path element of the URL to the resource you'd like to be rendered on the server. For example,
/
.
For example:
$VENV/bin/prequest development.ini /
This will print the body of the response to the console on which it was invoked.
Several options are supported by prequest
. These should precede any config
file name or URL.
prequest
has a -d
(i.e., --display-headers
) option which prints the
status and headers returned by the server before the output:
$VENV/bin/prequest -d development.ini /
This will print the status, headers, and the body of the response to the console.
You can add request header values by using the --header
option:
$VENV/bin/prequest --header=Host:example.com development.ini /
Headers are added to the WSGI environment by converting them to their CGI/WSGI
equivalents (e.g., Host=example.com
will insert the HTTP_HOST
header
variable as the value example.com
). Multiple --header
options can be
supplied. The special header value content-type
sets the CONTENT_TYPE
in the WSGI environment.
By default, prequest
sends a GET
request. You can change this by using
the -m
(aka --method
) option. GET
, HEAD
, POST
, and
DELETE
are currently supported. When you use POST
, the standard input
of the prequest
process is used as the POST
body:
$VENV/bin/prequest -mPOST development.ini / < somefile
pdistreport
: Showing All Installed Distributions and Their Versions¶
Added in version 1.5.
See also
See also the output of pdistreport --help.
You can use the pdistreport
command to show the Pyramid version in
use, the Python version in use, and all installed versions of Python
distributions in your Python environment:
$VENV/bin/pdistreport
Pyramid version: 1.5dev
Platform Linux-3.2.0-51-generic-x86_64-with-debian-wheezy-sid
Packages:
authapp 0.0
/home/chrism/projects/foo/src/authapp
beautifulsoup4 4.1.3
/home/chrism/projects/foo/lib/python2.7/site-packages/beautifulsoup4-4.1.3-py2.7.egg
# ... more output ...
pdistreport
takes no options. Its output is useful to paste into a
pastebin when you are having problems and need someone with more familiarity
with Python packaging and distribution than you have to look at your
environment.
Writing a Script¶
All web applications are, at their hearts, systems which accept a request and
return a response. When a request is accepted by a Pyramid application,
the system receives state from the request which is later relied on by your
application code. For example, one view callable may assume it's
working against a request that has a request.matchdict
of a particular
composition, while another assumes a different composition of the matchdict.
In the meantime, it's convenient to be able to write a Python script that can work "in a Pyramid environment", for instance to update database tables used by your Pyramid application. But a "real" Pyramid environment doesn't have a completely static state independent of a request; your application (and Pyramid itself) is almost always reliant on being able to obtain information from a request. When you run a Python script that simply imports code from your application and tries to run it, there just is no request data, because there isn't any real web request. Therefore some parts of your application and some Pyramid APIs will not work.
For this reason, Pyramid makes it possible to run a script in an
environment much like the environment produced when a particular
request reaches your Pyramid application. This is achieved by
using the pyramid.paster.bootstrap()
command in the body of your script.
Added in version 1.1: pyramid.paster.bootstrap()
Changed in version 1.8: Added the ability for bootstrap
to cleanup automatically via the
with
statement.
In the simplest case, pyramid.paster.bootstrap()
can be used with a
single argument, which accepts the PasteDeploy .ini
file
representing your Pyramid application's configuration as a single argument:
from pyramid.paster import bootstrap
with bootstrap('/path/to/my/development.ini') as env:
print(env['request'].route_url('home'))
pyramid.paster.bootstrap()
returns a dictionary containing
framework-related information. This dictionary will always contain a
request object as its request
key.
The following keys are available in the env
dictionary returned by
pyramid.paster.bootstrap()
:
request
A
pyramid.request.Request
object implying the current request state for your script.
app
The WSGI application object generated by bootstrapping.
root
The resource root of your Pyramid application. This is an object generated by the root factory configured in your application.
registry
The application registry of your Pyramid application.
closer
A parameterless callable that can be used to pop an internal Pyramid threadlocal stack (used by
pyramid.threadlocal.get_current_registry()
andpyramid.threadlocal.get_current_request()
) when your scripting job is finished.
Let's assume that the /path/to/my/development.ini
file used in the example
above looks like so:
[pipeline:main]
pipeline = translogger
another
[filter:translogger]
filter_app_factory = egg:Paste#translogger
setup_console_handler = False
logger_name = wsgi
[app:another]
use = egg:MyProject
The configuration loaded by the above bootstrap example will use the
configuration implied by the [pipeline:main]
section of your configuration
file by default. Specifying /path/to/my/development.ini
is logically
equivalent to specifying /path/to/my/development.ini#main
. In this case,
we'll be using a configuration that includes an app
object which is wrapped
in the Paste "translogger" middleware (which logs requests to the
console).
You can also specify a particular section of the PasteDeploy .ini
file to
load instead of main
:
from pyramid.paster import bootstrap
with bootstrap('/path/to/my/development.ini#another') as env:
print(env['request'].route_url('home'))
The above example specifies the another
app
, pipeline
, or
composite
section of your PasteDeploy configuration file. The app
object present in the env
dictionary returned by
pyramid.paster.bootstrap()
will be a Pyramid router.
Changing the Request¶
By default, Pyramid will generate a request object in the env
dictionary
for the URL http://localhost:80/
. This means that any URLs generated by
Pyramid during the execution of your script will be anchored here. This is
generally not what you want.
So how do we make Pyramid generate the correct URLs?
Assuming that you have a route configured in your application like so:
config.add_route('verify', '/verify/{code}')
You need to inform the Pyramid environment that the WSGI application is
handling requests from a certain base. For example, we want to simulate
mounting our application at https://example.com/prefix, to ensure that the
generated URLs are correct for our deployment. This can be done by either
mutating the resulting request object, or more simply by constructing the
desired request and passing it into bootstrap()
:
from pyramid.paster import bootstrap
from pyramid.request import Request
request = Request.blank('/', base_url='https://example.com/prefix')
with bootstrap('/path/to/my/development.ini#another', request=request) as env:
print(env['request'].application_url)
# will print 'https://example.com/prefix'
Now you can readily use Pyramid's APIs for generating URLs:
env['request'].route_url('verify', code='1337')
# will return 'https://example.com/prefix/verify/1337'
Cleanup¶
If you're using the with
-statement variant then there's nothing to
worry about. However if you're using the returned environment directly then
when your scripting logic finishes, it's good manners to call the closer
callback:
from pyramid.paster import bootstrap
env = bootstrap('/path/to/my/development.ini')
# .. do stuff ...
env['closer']()
Setting Up Logging¶
By default, pyramid.paster.bootstrap()
does not configure logging
parameters present in the configuration file. If you'd like to configure
logging based on [logger]
and related sections in the configuration file,
use the following command:
import pyramid.paster
pyramid.paster.setup_logging('/path/to/my/development.ini')
See Logging for more information on logging within Pyramid.
Making Your Script into a Console Script¶
A "console script" is Setuptools terminology for a script that gets
installed into the bin
directory of a Python virtual environment
(or "base" Python environment) when a distribution which houses that
script is installed. Because it's installed into the bin
directory of a
virtual environment when the distribution is installed, it's a convenient way
to package and distribute functionality that you can call from the
command-line. It's often more convenient to create a console script than it is
to create a .py
script and instruct people to call it with the "right"
Python interpreter. A console script generates a file that lives in bin
,
and when it's invoked it will always use the "right" Python environment, which
means it will always be invoked in an environment where all the libraries it
needs (such as Pyramid) are available.
In general, you can make your script into a console script by doing the following:
Use an existing distribution (such as one you've already created via
cookiecutter
) or create a new distribution that possesses at least one package or module. It should, within any module within the distribution, house a callable (usually a function) that takes no arguments and which runs any of the code you wish to run.Add a
[console_scripts]
section to theentry_points
argument of the distribution which creates a mapping between a script name and a dotted name representing the callable you added to your distribution.Run
pip install -e .
orpip install .
to get your distribution reinstalled. When you reinstall your distribution, a file representing the script that you named in the last step will be in thebin
directory of the virtual environment in which you installed the distribution. It will be executable. Invoking it from a terminal will execute your callable.
As an example, let's create some code that can be invoked by a console script
that prints the deployment settings of a Pyramid application. To do so, we'll
pretend you have a distribution with a package in it named myproject
.
Within this package, we'll pretend you've added a scripts.py
module which
contains the following code:
1# myproject.scripts module
2
3import optparse
4import sys
5import textwrap
6
7from pyramid.paster import bootstrap
8
9def settings_show():
10 description = """\
11 Print the deployment settings for a Pyramid application. Example:
12 'show_settings deployment.ini'
13 """
14 usage = "usage: %prog config_uri"
15 parser = optparse.OptionParser(
16 usage=usage,
17 description=textwrap.dedent(description)
18 )
19 parser.add_option(
20 '-o', '--omit',
21 dest='omit',
22 metavar='PREFIX',
23 type='string',
24 action='append',
25 help=("Omit settings which start with PREFIX (you can use this "
26 "option multiple times)")
27 )
28
29 options, args = parser.parse_args(sys.argv[1:])
30 if not len(args) >= 1:
31 print('You must provide at least one argument')
32 return 2
33 config_uri = args[0]
34 omit = options.omit
35 if omit is None:
36 omit = []
37 with bootstrap(config_uri) as env:
38 settings = env['registry'].settings
39 for k, v in settings.items():
40 if any([k.startswith(x) for x in omit]):
41 continue
42 print('%-40s %-20s' % (k, v))
This script uses the Python optparse
module to allow us to make sense out
of extra arguments passed to the script. It uses the
pyramid.paster.bootstrap()
function to get information about the
application defined by a config file, and prints the deployment settings
defined in that config file.
After adding this script to the package, you'll need to tell your
distribution's setup.py
about its existence. Within your distribution's
top-level directory, your setup.py
file will look something like this:
1import os
2
3from setuptools import setup, find_packages
4
5here = os.path.abspath(os.path.dirname(__file__))
6with open(os.path.join(here, 'README.txt')) as f:
7 README = f.read()
8with open(os.path.join(here, 'CHANGES.txt')) as f:
9 CHANGES = f.read()
10
11requires = ['pyramid', 'pyramid_debugtoolbar']
12
13tests_require = [
14 'WebTest',
15 'pytest',
16 'pytest-cov',
17]
18
19setup(name='MyProject',
20 version='0.0',
21 description='My project',
22 long_description=README + '\n\n' + CHANGES,
23 classifiers=[
24 "Programming Language :: Python",
25 "Framework :: Pyramid",
26 "Topic :: Internet :: WWW/HTTP",
27 "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
28 ],
29 author='',
30 author_email='',
31 url='',
32 keywords='web pyramid pylons',
33 packages=find_packages(exclude=['tests']),
34 include_package_data=True,
35 zip_safe=False,
36 install_requires=requires,
37 extras_require={
38 'testing': tests_require,
39 },
40 entry_points = """\
41 [paste.app_factory]
42 main = myproject:main
43 """,
44 )
We're going to change the setup.py
file to add a [console_scripts]
section within the entry_points
string. Within this section, you should
specify a scriptname = dotted.path.to:yourfunction
line. For example:
[console_scripts]
show_settings = myproject.scripts:settings_show
The show_settings
name will be the name of the script that is installed
into bin
. The colon (:
) between myproject.scripts
and
settings_show
above indicates that myproject.scripts
is a Python
module, and settings_show
is the function in that module which contains the
code you'd like to run as the result of someone invoking the show_settings
script from their command line.
The result will be something like:
1import os
2
3from setuptools import setup, find_packages
4
5here = os.path.abspath(os.path.dirname(__file__))
6with open(os.path.join(here, 'README.txt')) as f:
7 README = f.read()
8with open(os.path.join(here, 'CHANGES.txt')) as f:
9 CHANGES = f.read()
10
11requires = ['pyramid', 'pyramid_debugtoolbar']
12
13tests_require = [
14 'WebTest',
15 'pytest',
16 'pytest-cov',
17]
18
19setup(name='MyProject',
20 version='0.0',
21 description='My project',
22 long_description=README + '\n\n' + CHANGES,
23 classifiers=[
24 "Programming Language :: Python",
25 "Framework :: Pyramid",
26 "Topic :: Internet :: WWW/HTTP",
27 "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
28 ],
29 author='',
30 author_email='',
31 url='',
32 keywords='web pyramid pylons',
33 packages=find_packages(),
34 include_package_data=True,
35 zip_safe=False,
36 install_requires=requires,
37 extras_require={
38 'testing': tests_require,
39 },
40 entry_points = """\
41 [paste.app_factory]
42 main = myproject:main
43 [console_scripts]
44 show_settings = myproject.scripts:settings_show
45 """,
46)
Once you've done this, invoking $VENV/bin/pip install -e .
will install a
file named show_settings
into the $somevenv/bin
directory with a
small bit of Python code that points to your entry point. It will be
executable. Running it without any arguments will print an error and exit.
Running it with a single argument that is the path of a config file will print
the settings. Running it with an --omit=foo
argument will omit the settings
that have keys that start with foo
. Running it with two "omit" options
(e.g., --omit=foo --omit=bar
) will omit all settings that have keys that
start with either foo
or bar
:
$VENV/bin/show_settings development.ini --omit=pyramid --omit=debugtoolbar
debug_routematch False
debug_templates True
reload_templates True
mako.directories []
debug_notfound False
default_locale_name en
reload_resources False
debug_authorization False
reload_assets False
prevent_http_cache False
Pyramid's pserve
, pshell
, prequest
, ptweens
, and
other p*
scripts are implemented as console scripts. When you invoke one
of those, you are using a console script.