Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

20.7. MAKING YOUR SCRIPT INTO A CONSOLE SCRIPT

20.6.3 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 logging.config logging.config.fileConfig(’/path/to/my/development.ini’)

20.7 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 virtualenv (or “base” Python environment) when a distribution which houses that script is installed. Because it’s installed into the bin directory of a virtualenv 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 pcreate) 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 the entry_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 setup.py develop, setup.py install, or easy_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 the bin directory of the virtualenv 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:

223

20. COMMAND-LINE PYRAMID

1 # myproject.scripts module

2

3 import optparse

4 import sys

5 import textwrap

6

7 from pyramid.paster import bootstrap

8

9 def settings_show():

10description = """\

11Print the deployment settings for a Pyramid application. Example:

12’psettings deployment.ini’

13"""

14usage = "usage: %prog config_uri"

15parser = optparse.OptionParser(

16usage=usage,

17description=textwrap.dedent(description)

18)

19parser.add_option(

20’-o’, ’--omit’,

21dest=’omit’,

22metavar=’PREFIX’,

23type=’string’,

24action=’append’,

25help=("Omit settings which start with PREFIX (you can use this "

26

"option multiple times)")

27

)

28

29options, args = parser.parse_args(sys.argv[1:])

30if not len(args) >= 1:

31print(’You must provide at least one argument’)

32return 2

33config_uri = args[0]

34omit = options.omit

35if omit is None:

36omit = []

37env = bootstrap(config_uri)

38settings, closer = env[’registry’].settings, env[’closer’]

39try:

40for k, v in settings.items():

41

if any([k.startswith(x)

for x

in omit]):

42

continue

 

 

 

43

print(%-40s

%-20s

% (k,

v))

44finally:

45closer()

224

20.7. MAKING YOUR SCRIPT INTO A CONSOLE SCRIPT

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 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:

1

import os

2

 

3

from setuptools import setup, find_packages

4

 

5

here = os.path.abspath(os.path.dirname(__file__))

6

README = open(os.path.join(here, ’README.txt’)).read()

7

CHANGES = open(os.path.join(here, ’CHANGES.txt’)).read()

8

 

9

requires = [’pyramid’, ’pyramid_debugtoolbar’]

10

11setup(name=’MyProject’,

12version=’0.0’,

13description=’My project’,

14long_description=README + \n\n+ CHANGES,

15classifiers=[

16"Programming Language :: Python",

17"Framework :: Pylons",

18"Topic :: Internet :: WWW/HTTP",

19"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",

20],

21author=’’,

22author_email=’’,

23url=’’,

24keywords=’web pyramid pylons’,

25packages=find_packages(),

26include_package_data=True,

27zip_safe=False,

28install_requires=requires,

29tests_require=requires,

30test_suite="myproject",

31entry_points = """\

32[paste.app_factory]

33main = myproject:main

34""",

35)

We’re going to change the

setup.py file to add an

[console_scripts] section with in

the entry_points string.

Within this section,

you should specify a scriptname =

dotted.path.to:yourfunction line. For example:

 

225

20. COMMAND-LINE PYRAMID

[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:

1

import os

2

 

3

from setuptools import setup, find_packages

4

 

5

here = os.path.abspath(os.path.dirname(__file__))

6

README = open(os.path.join(here, ’README.txt’)).read()

7

CHANGES = open(os.path.join(here, ’CHANGES.txt’)).read()

8

 

9

requires = [’pyramid’, ’pyramid_debugtoolbar’]

10

11setup(name=’MyProject’,

12version=’0.0’,

13description=’My project’,

14long_description=README + \n\n+ CHANGES,

15classifiers=[

16"Programming Language :: Python",

17"Framework :: Pylons",

18"Topic :: Internet :: WWW/HTTP",

19"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",

20],

21author=’’,

22author_email=’’,

23url=’’,

24keywords=’web pyramid pylons’,

25packages=find_packages(),

26include_package_data=True,

27zip_safe=False,

28install_requires=requires,

29tests_require=requires,

30test_suite="myproject",

31entry_points = """\

32[paste.app_factory]

33main = myproject:main

34[console_scripts]

35show_settings = myproject.scripts:settings_show

226

20.7. MAKING YOUR SCRIPT INTO A CONSOLE SCRIPT

36

37

""",

)

Once you’ve done this, invoking $somevirtualenv/bin/python setup.py develop will install a file named show_settings into the $somevirtualenv/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:

[chrism@thinko somevenv]$ 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, pcreate, pshell, prequest, ptweens and other p* scripts are implemented as console scripts. When you invoke one of those, you are using a console script.

227

20. COMMAND-LINE PYRAMID

228

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]