Debian Codegraph @

lib-python/3/venv/__init__.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 Virtual environment (venv) package for Python. Based on PEP 405.
3
4 Copyright (C) 2011-2014 Vinay Sajip.
5 Licensed to the PSF under a contributor agreement.
6 """
7 import logging
8 import os
9 import shutil
10 import subprocess
11 import sys
12 import sysconfig
13 import types
14 import shlex
15
16
17 CORE_VENV_DEPS = ('pip', 'setuptools')
18 logger = logging.getLogger(__name__)
19
20 IS_PYPY = sys.implementation.name == 'pypy'
21
22 class EnvBuilder:
23 """
24 This class exists to allow virtual environment creation to be
25 customized. The constructor parameters determine the builder's
26 behaviour when called upon to create a virtual environment.
27
28 By default, the builder makes the system (global) site-packages dir
29 *un*available to the created environment.
30
31 If invoked using the Python -m option, the default is to use copying
32 on Windows platforms but symlinks elsewhere. If instantiated some
33 other way, the default is to *not* use symlinks.
34
35 :param system_site_packages: If True, the system (global) site-packages
36 dir is available to created environments.
37 :param clear: If True, delete the contents of the environment directory if
38 it already exists, before environment creation.
39 :param symlinks: If True, attempt to symlink rather than copy files into
40 virtual environment.
41 :param upgrade: If True, upgrade an existing virtual environment.
42 :param with_pip: If True, ensure pip is installed in the virtual
43 environment
44 :param prompt: Alternative terminal prefix for the environment.
45 :param upgrade_deps: Update the base venv modules to the latest on PyPI
46 """
47
48 def __init__(self, system_site_packages=False, clear=False,
49 symlinks=False, upgrade=False, with_pip=False, prompt=None,
50 upgrade_deps=False):
51 self.system_site_packages = system_site_packages
52 self.clear = clear
53 self.symlinks = symlinks
54 self.upgrade = upgrade
55 self.with_pip = with_pip
56 self.orig_prompt = prompt
57 if prompt == '.': # see bpo-38901
58 prompt = os.path.basename(os.getcwd())
59 self.prompt = prompt
60 self.upgrade_deps = upgrade_deps
61
62 def create(self, env_dir):
63 """
64 Create a virtual environment in a directory.
65
66 :param env_dir: The target directory to create an environment in.
67
68 """
69 env_dir = os.path.abspath(env_dir)
70 context = self.ensure_directories(env_dir)
71 # See issue 24875. We need system_site_packages to be False
72 # until after pip is installed.
73 true_system_site_packages = self.system_site_packages
74 self.system_site_packages = False
75 self.create_configuration(context)
76 self.setup_python(context)
77 if self.with_pip:
78 self._setup_pip(context)
79 if not self.upgrade:
80 self.setup_scripts(context)
81 self.post_setup(context)
82 if true_system_site_packages:
83 # We had set it to False before, now
84 # restore it and rewrite the configuration
85 self.system_site_packages = True
86 self.create_configuration(context)
87 if self.upgrade_deps:
88 self.upgrade_dependencies(context)
89
90 def clear_directory(self, path):
91 for fn in os.listdir(path):
92 fn = os.path.join(path, fn)
93 if os.path.islink(fn) or os.path.isfile(fn):
94 os.remove(fn)
95 elif os.path.isdir(fn):
96 shutil.rmtree(fn)
97
98 def _venv_path(self, env_dir, name):
99 vars = {
100 'base': env_dir,
101 'platbase': env_dir,
102 'installed_base': env_dir,
103 'installed_platbase': env_dir,
104 }
105 return sysconfig.get_path(name, scheme='venv', vars=vars)
106
107 def ensure_directories(self, env_dir):
108 """
109 Create the directories for the environment.
110
111 Returns a context object which holds paths in the environment,
112 for use by subsequent logic.
113 """
114
115 def create_if_needed(d):
116 if not os.path.exists(d):
117 os.makedirs(d)
118 elif os.path.islink(d) or os.path.isfile(d):
119 raise ValueError('Unable to create directory %r' % d)
120
121 if os.pathsep in os.fspath(env_dir):
122 raise ValueError(f'Refusing to create a venv in {env_dir} because '
123 f'it contains the PATH separator {os.pathsep}.')
124 if os.path.exists(env_dir) and self.clear:
125 self.clear_directory(env_dir)
126 context = types.SimpleNamespace()
127 context.env_dir = env_dir
128 context.env_name = os.path.split(env_dir)[1]
129 prompt = self.prompt if self.prompt is not None else context.env_name
130 context.prompt = '(%s) ' % prompt
131 create_if_needed(env_dir)
132 executable = sys._base_executable
133 if not executable: # see gh-96861
134 raise ValueError('Unable to determine path to the running '
135 'Python interpreter. Provide an explicit path or '
136 'check that your PATH environment variable is '
137 'correctly set.')
138 dirname, exename = os.path.split(os.path.abspath(executable))
139 context.executable = executable
140 context.python_dir = dirname
141 context.python_exe = exename
142 binpath = self._venv_path(env_dir, 'scripts')
143 incpath = self._venv_path(env_dir, 'include')
144 libpath = self._venv_path(env_dir, 'purelib')
145
146 context.inc_path = incpath
147 create_if_needed(incpath)
148 create_if_needed(libpath)
149 # Issue 21197: create lib64 as a symlink to lib on 64-bit non-OS X POSIX
150 if ((sys.maxsize > 2**32) and (os.name == 'posix') and
151 (sys.platform != 'darwin')):
152 link_path = os.path.join(env_dir, 'lib64')
153 if not os.path.exists(link_path): # Issue #21643
154 os.symlink('lib', link_path)
155 context.bin_path = binpath
156 context.bin_name = os.path.relpath(binpath, env_dir)
157 context.env_exe = os.path.join(binpath, exename)
158 create_if_needed(binpath)
159 # Assign and update the command to use when launching the newly created
160 # environment, in case it isn't simply the executable script (e.g. bpo-45337)
161 context.env_exec_cmd = context.env_exe
162 if sys.platform == 'win32':
163 # bpo-45337: Fix up env_exec_cmd to account for file system redirections.
164 # Some redirects only apply to CreateFile and not CreateProcess
165 real_env_exe = os.path.realpath(context.env_exe)
166 if os.path.normcase(real_env_exe) != os.path.normcase(context.env_exe):
167 logger.warning('Actual environment location may have moved due to '
168 'redirects, links or junctions.\n'
169 ' Requested location: "%s"\n'
170 ' Actual location: "%s"',
171 context.env_exe, real_env_exe)
172 context.env_exec_cmd = real_env_exe
173 return context
174
175 def create_configuration(self, context):
176 """
177 Create a configuration file indicating where the environment's Python
178 was copied from, and whether the system site-packages should be made
179 available in the environment.
180
181 :param context: The information for the environment creation request
182 being processed.
183 """
184 context.cfg_path = path = os.path.join(context.env_dir, 'pyvenv.cfg')
185 with open(path, 'w', encoding='utf-8') as f:
186 f.write('home = %s\n' % context.python_dir)
187 if self.system_site_packages:
188 incl = 'true'
189 else:
190 incl = 'false'
191 f.write('include-system-site-packages = %s\n' % incl)
192 f.write('version = %d.%d.%d\n' % sys.version_info[:3])
193 if self.prompt is not None:
194 f.write(f'prompt = {self.prompt!r}\n')
195 f.write('executable = %s\n' % os.path.realpath(sys.executable))
196 args = []
197 nt = os.name == 'nt'
198 if nt and self.symlinks:
199 args.append('--symlinks')
200 if not nt and not self.symlinks:
201 args.append('--copies')
202 if not self.with_pip:
203 args.append('--without-pip')
204 if self.system_site_packages:
205 args.append('--system-site-packages')
206 if self.clear:
207 args.append('--clear')
208 if self.upgrade:
209 args.append('--upgrade')
210 if self.upgrade_deps:
211 args.append('--upgrade-deps')
212 if self.orig_prompt is not None:
213 args.append(f'--prompt="{self.orig_prompt}"')
214
215 args.append(context.env_dir)
216 args = ' '.join(args)
217 f.write(f'command = {sys.executable} -m venv {args}\n')
218
219 if os.name != 'nt':
220 def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
221 """
222 Try symlinking a file, and if that fails, fall back to copying.
223 """
224 force_copy = not self.symlinks
225 if not force_copy:
226 try:
227 if not os.path.islink(dst): # can't link to itself!
228 if relative_symlinks_ok:
229 assert os.path.dirname(src) == os.path.dirname(dst)
230 os.symlink(os.path.basename(src), dst)
231 else:
232 os.symlink(src, dst)
233 except Exception: # may need to use a more specific exception
234 logger.warning('Unable to symlink %r to %r', src, dst)
235 force_copy = True
236 if force_copy:
237 if os.path.isdir(src):
238 shutil.copytree(src, dst)
239 elif os.path.islink(src):
240 # On PyPy, creating a copy of a symlinked-venv must still
241 # point back to the original file since the exe needs
242 # libpypy* and perhaps other 'portable' shared objects
243 final = os.path.realpath(src)
244 os.symlink(final, dst)
245 else:
246 shutil.copyfile(src, dst)
247 else:
248 def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
249 """
250 Try symlinking a file, and if that fails, fall back to copying.
251 """
252 bad_src = os.path.lexists(src) and not os.path.exists(src)
253 if self.symlinks and not bad_src and not os.path.islink(dst):
254 try:
255 if relative_symlinks_ok:
256 assert os.path.dirname(src) == os.path.dirname(dst)
257 os.symlink(os.path.basename(src), dst)
258 else:
259 os.symlink(src, dst)
260 return
261 except Exception: # may need to use a more specific exception
262 logger.warning('Unable to symlink %r to %r', src, dst)
263
264 # On Windows, we rewrite symlinks to our base python.exe into
265 # copies of venvlauncher.exe
266 basename, ext = os.path.splitext(os.path.basename(src))
267 srcfn = os.path.join(os.path.dirname(__file__),
268 "scripts",
269 "nt",
270 basename + ext)
271 # Builds or venv's from builds need to remap source file
272 # locations, as we do not put them into Lib/venv/scripts
273 if sysconfig.is_python_build() or not os.path.isfile(srcfn):
274 if basename.endswith('_d'):
275 ext = '_d' + ext
276 basename = basename[:-2]
277 if not IS_PYPY and basename == 'python':
278 basename = 'venvlauncher'
279 elif not IS_PYPY and basename == 'pythonw':
280 basename = 'venvwlauncher'
281 src = os.path.join(os.path.dirname(src), basename + ext)
282 else:
283 src = srcfn
284 if not os.path.exists(src):
285 if not bad_src:
286 logger.warning('Unable to copy %r', src)
287 return
288
289 shutil.copyfile(src, dst)
290
291 def setup_python(self, context):
292 """
293 Set up a Python executable in the environment.
294
295 :param context: The information for the environment creation request
296 being processed.
297 """
298 binpath = context.bin_path
299 path = context.env_exe
300 copier = self.symlink_or_copy
301 dirname = context.python_dir
302 if os.name != 'nt':
303 copier(context.executable, path)
304 if not os.path.islink(path):
305 os.chmod(path, 0o755)
306 for suffix in ('python', 'python3', f'python3.{sys.version_info[1]}', 'pypy3', 'pypy'):
307 path = os.path.join(binpath, suffix)
308 if not os.path.exists(path):
309 # Issue 18807: make copies if
310 # symlinks are not wanted
311 copier(context.env_exe, path, relative_symlinks_ok=True)
312 if not os.path.islink(path):
313 os.chmod(path, 0o755)
314 if not self.symlinks:
315 #
316 # PyPy extension: also copy the main library, not just the
317 # small executable
318 for libname in ['libpypy3.11-c.so', 'libpypy3.11-c.dylib']:
319 dest_library = os.path.join(binpath, libname)
320 src_library = os.path.join(os.path.dirname(context.executable),
321 libname)
322 if (not os.path.exists(dest_library) and
323 os.path.exists(src_library)):
324 copier(src_library, dest_library)
325 if not os.path.islink(dest_library):
326 os.chmod(dest_library, 0o755)
327 libsrc = os.path.join(context.python_dir, '..', 'lib')
328 deps_file = os.path.join(libsrc, "PYPY_PORTABLE_DEPS.txt")
329 if os.path.exists(libsrc) and os.path.exists(deps_file):
330 # PyPy: also copy lib/*.so*, lib/tk, lib/tcl for portable
331 # builds
332 libdst = os.path.join(context.env_dir, 'lib')
333 if not os.path.exists(libdst):
334 os.mkdir(libdst)
335 with open(deps_file, encoding="utf-8") as fid:
336 for f in fid:
337 src = os.path.join(libsrc, f.strip())
338 dst = os.path.join(libdst, f.strip())
339 if os.path.exists(src):
340 if os.path.exists(dst):
341 # skip directories when upgrading
342 continue
343 copier(src, dst)
344 #
345 else:
346 if self.symlinks:
347 # For symlinking, we need a complete copy of the root directory
348 # If symlinks fail, you'll get unnecessary copies of files, but
349 # we assume that if you've opted into symlinks on Windows then
350 # you know what you're doing.
351 suffixes = [
352 f for f in os.listdir(dirname) if
353 os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
354 ]
355 if sysconfig.is_python_build():
356 suffixes = [
357 f for f in suffixes if
358 os.path.normcase(f).startswith(('python', 'vcruntime'))
359 ]
360 else:
361 # PyPy change: since PyPy does not use a PEP 397 launcher,
362 # copy all the exes and dlls.
363 suffixes = [
364 f for f in os.listdir(dirname) if
365 os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
366 ]
367 base_exe = os.path.basename(context.env_exe)
368 suffixes.append(base_exe)
369
370 for suffix in suffixes:
371 src = os.path.join(dirname, suffix)
372 if os.path.lexists(src):
373 copier(src, os.path.join(binpath, suffix))
374
375 exe = os.path.split(sys.executable)[1].lower()
376 if exe not in suffixes:
377 if "pypy3.11-c.exe" in suffixes:
378 # dirname is a source build, with only the
379 # pypy*-c.exe? Make sure to create
380 # sys.executable as well
381 src = os.path.join(dirname, "pypy3.11-c.exe")
382 dst = os.path.join(binpath, exe)
383 copier(src, dst)
384 elif not suffixes:
385 # dirname is a source build from dirname\pypy\goal
386 # so add that to dirname and try again
387 dirname = os.path.join(dirname, "pypy", "goal")
388 suffixes = [
389 f for f in os.listdir(dirname) if
390 os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
391 ]
392 for suffix in suffixes:
393 src = os.path.join(dirname, suffix)
394 if os.path.lexists(src):
395 copier(src, os.path.join(binpath, suffix))
396 src = os.path.join(dirname, "pypy3.11-c.exe")
397 if src != context.env_exec_cmd:
398 copier(src, context.env_exec_cmd)
399 copier(src, os.path.join(binpath, "python.exe"))
400 copier(src, os.path.join(binpath, "python3.exe"))
401 else:
402 raise RuntimeError(f"problem finding exe {exe} in {suffixes}")
403
404 if sysconfig.is_python_build(True):
405 # copy init.tcl
406 for root, dirs, files in os.walk(context.python_dir):
407 if 'init.tcl' in files:
408 tcldir = os.path.basename(root)
409 tcldir = os.path.join(context.env_dir, 'Lib', tcldir)
410 if not os.path.exists(tcldir):
411 os.makedirs(tcldir)
412 src = os.path.join(root, 'init.tcl')
413 dst = os.path.join(tcldir, 'init.tcl')
414 shutil.copyfile(src, dst)
415 break
416
417 def _call_new_python(self, context, *py_args, **kwargs):
418 """Executes the newly created Python using safe-ish options"""
419 # gh-98251: We do not want to just use '-I' because that masks
420 # legitimate user preferences (such as not writing bytecode). All we
421 # really need is to ensure that the path variables do not overrule
422 # normal venv handling.
423 args = [context.env_exec_cmd, *py_args]
424 kwargs['env'] = env = os.environ.copy()
425 env['VIRTUAL_ENV'] = context.env_dir
426 env.pop('PYTHONHOME', None)
427 env.pop('PYTHONPATH', None)
428 kwargs['cwd'] = context.env_dir
429 kwargs['executable'] = context.env_exec_cmd
430 subprocess.check_output(args, **kwargs)
431
432 def _setup_pip(self, context):
433 """Installs or upgrades pip in a virtual environment"""
434 self._call_new_python(context, '-m', 'ensurepip', '--upgrade',
435 '--default-pip', stderr=subprocess.STDOUT)
436
437 def setup_scripts(self, context):
438 """
439 Set up scripts into the created environment from a directory.
440
441 This method installs the default scripts into the environment
442 being created. You can prevent the default installation by overriding
443 this method if you really need to, or if you need to specify
444 a different location for the scripts to install. By default, the
445 'scripts' directory in the venv package is used as the source of
446 scripts to install.
447 """
448 path = os.path.abspath(os.path.dirname(__file__))
449 path = os.path.join(path, 'scripts')
450 self.install_scripts(context, path)
451
452 def post_setup(self, context):
453 """
454 Hook for post-setup modification of the venv. Subclasses may install
455 additional packages or scripts here, add activation shell scripts, etc.
456
457 :param context: The information for the environment creation request
458 being processed.
459 """
460 pass
461
462 def replace_variables(self, text, context):
463 """
464 Replace variable placeholders in script text with context-specific
465 variables.
466
467 Return the text passed in , but with variables replaced.
468
469 :param text: The text in which to replace placeholder variables.
470 :param context: The information for the environment creation request
471 being processed.
472 """
473 replacements = {
474 '__VENV_DIR__': context.env_dir,
475 '__VENV_NAME__': context.env_name,
476 '__VENV_PROMPT__': context.prompt,
477 '__VENV_BIN_NAME__': context.bin_name,
478 '__VENV_PYTHON__': context.env_exe,
479 }
480
481 def quote_ps1(s):
482 """
483 This should satisfy PowerShell quoting rules [1], unless the quoted
484 string is passed directly to Windows native commands [2].
485 [1]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
486 [2]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing#passing-arguments-that-contain-quote-characters
487 """
488 s = s.replace("'", "''")
489 return f"'{s}'"
490
491 def quote_bat(s):
492 return s
493
494 # gh-124651: need to quote the template strings properly
495 quote = shlex.quote
496 script_path = context.script_path
497 if script_path.endswith('.ps1'):
498 quote = quote_ps1
499 elif script_path.endswith('.bat'):
500 quote = quote_bat
501 else:
502 # fallbacks to POSIX shell compliant quote
503 quote = shlex.quote
504
505 replacements = {key: quote(s) for key, s in replacements.items()}
506 for key, quoted in replacements.items():
507 text = text.replace(key, quoted)
508 return text
509
510 def install_scripts(self, context, path):
511 """
512 Install scripts into the created environment from a directory.
513
514 :param context: The information for the environment creation request
515 being processed.
516 :param path: Absolute pathname of a directory containing script.
517 Scripts in the 'common' subdirectory of this directory,
518 and those in the directory named for the platform
519 being run on, are installed in the created environment.
520 Placeholder variables are replaced with environment-
521 specific values.
522 """
523 binpath = context.bin_path
524 plen = len(path)
525 for root, dirs, files in os.walk(path):
526 if root == path: # at top-level, remove irrelevant dirs
527 for d in dirs[:]:
528 if d not in ('common', os.name):
529 dirs.remove(d)
530 continue # ignore files in top level
531 for f in files:
532 if (os.name == 'nt' and f.startswith('python')
533 and f.endswith(('.exe', '.pdb'))):
534 continue
535 srcfile = os.path.join(root, f)
536 suffix = root[plen:].split(os.sep)[2:]
537 if not suffix:
538 dstdir = binpath
539 else:
540 dstdir = os.path.join(binpath, *suffix)
541 if not os.path.exists(dstdir):
542 os.makedirs(dstdir)
543 dstfile = os.path.join(dstdir, f)
544 with open(srcfile, 'rb') as f:
545 data = f.read()
546 if not srcfile.endswith(('.exe', '.pdb')):
547 context.script_path = srcfile
548 try:
549 data = data.decode('utf-8')
550 data = self.replace_variables(data, context)
551 data = data.encode('utf-8')
552 except UnicodeError as e:
553 data = None
554 logger.warning('unable to copy script %r, '
555 'may be binary: %s', srcfile, e)
556 if data is not None:
557 with open(dstfile, 'wb') as f:
558 f.write(data)
559 shutil.copymode(srcfile, dstfile)
560
561 def upgrade_dependencies(self, context):
562 logger.debug(
563 f'Upgrading {CORE_VENV_DEPS} packages in {context.bin_path}'
564 )
565 self._call_new_python(context, '-m', 'pip', 'install', '--upgrade',
566 *CORE_VENV_DEPS)
567
568
569 def create(env_dir, system_site_packages=False, clear=False,
570 symlinks=False, with_pip=False, prompt=None, upgrade_deps=False):
571 """Create a virtual environment in a directory."""
572 builder = EnvBuilder(system_site_packages=system_site_packages,
573 clear=clear, symlinks=symlinks, with_pip=with_pip,
574 prompt=prompt, upgrade_deps=upgrade_deps)
575 builder.create(env_dir)
576
577 def main(args=None):
578 compatible = True
579 if sys.version_info < (3, 3):
580 compatible = False
581 elif not hasattr(sys, 'base_prefix'):
582 compatible = False
583 if not compatible:
584 raise ValueError('This script is only for use with Python >= 3.3')
585 else:
586 import argparse
587
588 parser = argparse.ArgumentParser(prog=__name__,
589 description='Creates virtual Python '
590 'environments in one or '
591 'more target '
592 'directories.',
593 epilog='Once an environment has been '
594 'created, you may wish to '
595 'activate it, e.g. by '
596 'sourcing an activate script '
597 'in its bin directory.')
598 parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
599 help='A directory to create the environment in.')
600 parser.add_argument('--system-site-packages', default=False,
601 action='store_true', dest='system_site',
602 help='Give the virtual environment access to the '
603 'system site-packages dir.')
604 if os.name == 'nt':
605 use_symlinks = False
606 else:
607 use_symlinks = True
608 group = parser.add_mutually_exclusive_group()
609 group.add_argument('--symlinks', default=use_symlinks,
610 action='store_true', dest='symlinks',
611 help='Try to use symlinks rather than copies, '
612 'when symlinks are not the default for '
613 'the platform.')
614 group.add_argument('--copies', default=not use_symlinks,
615 action='store_false', dest='symlinks',
616 help='Try to use copies rather than symlinks, '
617 'even when symlinks are the default for '
618 'the platform.')
619 parser.add_argument('--clear', default=False, action='store_true',
620 dest='clear', help='Delete the contents of the '
621 'environment directory if it '
622 'already exists, before '
623 'environment creation.')
624 parser.add_argument('--upgrade', default=False, action='store_true',
625 dest='upgrade', help='Upgrade the environment '
626 'directory to use this version '
627 'of Python, assuming Python '
628 'has been upgraded in-place.')
629 parser.add_argument('--without-pip', dest='with_pip',
630 default=True, action='store_false',
631 help='Skips installing or upgrading pip in the '
632 'virtual environment (pip is bootstrapped '
633 'by default)')
634 parser.add_argument('--prompt',
635 help='Provides an alternative prompt prefix for '
636 'this environment.')
637 parser.add_argument('--upgrade-deps', default=False, action='store_true',
638 dest='upgrade_deps',
639 help='Upgrade core dependencies: {} to the latest '
640 'version in PyPI'.format(
641 ' '.join(CORE_VENV_DEPS)))
642 options = parser.parse_args(args)
643 if options.upgrade and options.clear:
644 raise ValueError('you cannot supply --upgrade and --clear together.')
645 builder = EnvBuilder(system_site_packages=options.system_site,
646 clear=options.clear,
647 symlinks=options.symlinks,
648 upgrade=options.upgrade,
649 with_pip=options.with_pip,
650 prompt=options.prompt,
651 upgrade_deps=options.upgrade_deps)
652 for d in options.dirs:
653 builder.create(d)
654
655 if __name__ == '__main__':
656 rc = 1
657 try:
658 main()
659 rc = 0
660 except Exception as e:
661 print('Error: %s' % e, file=sys.stderr)
662 sys.exit(rc)