PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/interpreter/app_main.py

https://bitbucket.org/kcr/pypy
Python | 772 lines | 660 code | 52 blank | 60 comment | 103 complexity | c08ddac4641cc1012239cf176cc73e3c MD5 | raw file
Possible License(s): Apache-2.0
  1. #! /usr/bin/env python
  2. # App-level version of py.py.
  3. # See test/test_app_main.
  4. """
  5. options:
  6. -i inspect interactively after running script
  7. -O dummy optimization flag for compatibility with C Python
  8. -c cmd program passed in as CMD (terminates option list)
  9. -S do not 'import site' on initialization
  10. -u unbuffered binary stdout and stderr
  11. -h, --help show this help message and exit
  12. -m mod library module to be run as a script (terminates option list)
  13. -W arg warning control (arg is action:message:category:module:lineno)
  14. -E ignore environment variables (such as PYTHONPATH)
  15. -R ignored (see http://bugs.python.org/issue14621)
  16. --version print the PyPy version
  17. --info print translation information about this PyPy executable
  18. """
  19. import sys
  20. DEBUG = False # dump exceptions before calling the except hook
  21. originalexcepthook = sys.__excepthook__
  22. def handle_sys_exit(e):
  23. # exit if we catch a w_SystemExit
  24. exitcode = e.code
  25. if exitcode is None:
  26. exitcode = 0
  27. else:
  28. try:
  29. exitcode = int(exitcode)
  30. except:
  31. # not an integer: print it to stderr
  32. try:
  33. print >> sys.stderr, exitcode
  34. except:
  35. pass # too bad
  36. exitcode = 1
  37. raise SystemExit(exitcode)
  38. def run_toplevel(f, *fargs, **fkwds):
  39. """Calls f() and handles all OperationErrors.
  40. Intended use is to run the main program or one interactive statement.
  41. run_protected() handles details like forwarding exceptions to
  42. sys.excepthook(), catching SystemExit, printing a newline after
  43. sys.stdout if needed, etc.
  44. """
  45. try:
  46. # run it
  47. f(*fargs, **fkwds)
  48. # we arrive here if no exception is raised. stdout cosmetics...
  49. try:
  50. stdout = sys.stdout
  51. softspace = stdout.softspace
  52. except AttributeError:
  53. pass
  54. # Don't crash if user defined stdout doesn't have softspace
  55. else:
  56. if softspace:
  57. stdout.write('\n')
  58. except SystemExit, e:
  59. handle_sys_exit(e)
  60. except:
  61. display_exception()
  62. return False
  63. return True # success
  64. def display_exception():
  65. etype, evalue, etraceback = sys.exc_info()
  66. try:
  67. # extra debugging info in case the code below goes very wrong
  68. if DEBUG and hasattr(sys, 'stderr'):
  69. s = getattr(etype, '__name__', repr(etype))
  70. print >> sys.stderr, "debug: exception-type: ", s
  71. print >> sys.stderr, "debug: exception-value:", str(evalue)
  72. tbentry = etraceback
  73. if tbentry:
  74. while tbentry.tb_next:
  75. tbentry = tbentry.tb_next
  76. lineno = tbentry.tb_lineno
  77. filename = tbentry.tb_frame.f_code.co_filename
  78. print >> sys.stderr, "debug: exception-tb: %s:%d" % (
  79. filename, lineno)
  80. # set the sys.last_xxx attributes
  81. sys.last_type = etype
  82. sys.last_value = evalue
  83. sys.last_traceback = etraceback
  84. # call sys.excepthook
  85. hook = getattr(sys, 'excepthook', originalexcepthook)
  86. hook(etype, evalue, etraceback)
  87. return # done
  88. except:
  89. try:
  90. stderr = sys.stderr
  91. except AttributeError:
  92. pass # too bad
  93. else:
  94. print >> stderr, 'Error calling sys.excepthook:'
  95. originalexcepthook(*sys.exc_info())
  96. print >> stderr
  97. print >> stderr, 'Original exception was:'
  98. # we only get here if sys.excepthook didn't do its job
  99. originalexcepthook(etype, evalue, etraceback)
  100. # ____________________________________________________________
  101. # Option parsing
  102. def print_info(*args):
  103. try:
  104. options = sys.pypy_translation_info
  105. except AttributeError:
  106. print >> sys.stderr, 'no translation information found'
  107. else:
  108. optitems = sorted(options.items())
  109. current = []
  110. for key, value in optitems:
  111. group = key.split('.')
  112. name = group.pop()
  113. n = 0
  114. while n < min(len(current), len(group)) and current[n] == group[n]:
  115. n += 1
  116. while n < len(group):
  117. print '%s[%s]' % (' ' * n, group[n])
  118. n += 1
  119. print '%s%s = %r' % (' ' * n, name, value)
  120. current = group
  121. raise SystemExit
  122. def print_help(*args):
  123. print 'usage: %s [options] [-c cmd|-m mod|file.py|-] [arg...]' % (
  124. sys.executable,)
  125. print __doc__.rstrip()
  126. if 'pypyjit' in sys.builtin_module_names:
  127. print " --jit OPTIONS advanced JIT options: try 'off' or 'help'"
  128. print
  129. raise SystemExit
  130. def _print_jit_help():
  131. try:
  132. import pypyjit
  133. except ImportError:
  134. print >> sys.stderr, "No jit support in %s" % (sys.executable,)
  135. return
  136. items = sorted(pypyjit.defaults.items())
  137. print 'Advanced JIT options: a comma-separated list of OPTION=VALUE:'
  138. for key, value in items:
  139. print
  140. print ' %s=N' % (key,)
  141. doc = '%s (default %s)' % (pypyjit.PARAMETER_DOCS[key], value)
  142. while len(doc) > 72:
  143. i = doc[:74].rfind(' ')
  144. if i < 0:
  145. i = doc.find(' ')
  146. if i < 0:
  147. i = len(doc)
  148. print ' ' + doc[:i]
  149. doc = doc[i+1:]
  150. print ' ' + doc
  151. print
  152. print ' off'
  153. print ' turn off the JIT'
  154. print ' help'
  155. print ' print this page'
  156. def print_version(*args):
  157. print >> sys.stderr, "Python", sys.version
  158. raise SystemExit
  159. def set_jit_option(options, jitparam, *args):
  160. if jitparam == 'help':
  161. _print_jit_help()
  162. raise SystemExit
  163. if 'pypyjit' not in sys.builtin_module_names:
  164. print >> sys.stderr, ("Warning: No jit support in %s" %
  165. (sys.executable,))
  166. else:
  167. import pypyjit
  168. pypyjit.set_param(jitparam)
  169. class CommandLineError(Exception):
  170. pass
  171. def print_error(msg):
  172. print >> sys.stderr, msg
  173. print >> sys.stderr, 'usage: %s [options]' % (sys.executable,)
  174. print >> sys.stderr, 'Try `%s -h` for more information.' % (sys.executable,)
  175. def fdopen(fd, mode, bufsize=-1):
  176. try:
  177. fdopen = file.fdopen
  178. except AttributeError: # only on top of CPython, running tests
  179. from os import fdopen
  180. return fdopen(fd, mode, bufsize)
  181. def set_unbuffered_io():
  182. sys.stdin = sys.__stdin__ = fdopen(0, 'rb', 0)
  183. sys.stdout = sys.__stdout__ = fdopen(1, 'wb', 0)
  184. sys.stderr = sys.__stderr__ = fdopen(2, 'wb', 0)
  185. def set_fully_buffered_io():
  186. sys.stdout = sys.__stdout__ = fdopen(1, 'w')
  187. # ____________________________________________________________
  188. # Main entry point
  189. def we_are_translated():
  190. # app-level, very different from rpython.rlib.objectmodel.we_are_translated
  191. return hasattr(sys, 'pypy_translation_info')
  192. IS_WINDOWS = 'nt' in sys.builtin_module_names
  193. def setup_and_fix_paths(ignore_environment=False, **extra):
  194. import os
  195. newpath = sys.path[:]
  196. del sys.path[:]
  197. # first prepend PYTHONPATH
  198. readenv = not ignore_environment
  199. path = readenv and os.getenv('PYTHONPATH')
  200. if path:
  201. sys.path.extend(path.split(os.pathsep))
  202. # then add again the original entries, ignoring duplicates
  203. _seen = set()
  204. for dir in newpath:
  205. if dir not in _seen:
  206. sys.path.append(dir)
  207. _seen.add(dir)
  208. def set_stdio_encodings(ignore_environment):
  209. import os
  210. readenv = not ignore_environment
  211. io_encoding = readenv and os.getenv("PYTHONIOENCODING")
  212. if io_encoding:
  213. errors = None
  214. if ":" in io_encoding:
  215. io_encoding, errors = io_encoding.split(":", 1)
  216. set_io_encoding(io_encoding, io_encoding, errors, True)
  217. else:
  218. if IS_WINDOWS:
  219. import __pypy__
  220. io_encoding, io_encoding_output = __pypy__.get_console_cp()
  221. else:
  222. io_encoding = io_encoding_output = sys.getfilesystemencoding()
  223. if io_encoding:
  224. set_io_encoding(io_encoding, io_encoding_output, None, False)
  225. def set_io_encoding(io_encoding, io_encoding_output, errors, overridden):
  226. try:
  227. import _file
  228. except ImportError:
  229. if sys.version_info < (2, 7):
  230. return
  231. # HACK: while running on top of CPython, and make sure to import
  232. # CPython's ctypes (because at this point sys.path has already been
  233. # set to the pypy one)
  234. pypy_path = sys.path
  235. try:
  236. sys.path = sys.cpython_path
  237. import ctypes
  238. finally:
  239. sys.path = pypy_path
  240. set_file_encoding = ctypes.pythonapi.PyFile_SetEncodingAndErrors
  241. set_file_encoding.argtypes = [ctypes.py_object, ctypes.c_char_p, ctypes.c_char_p]
  242. else:
  243. set_file_encoding = _file.set_file_encoding
  244. for f, encoding in [(sys.stdin, io_encoding),
  245. (sys.stdout, io_encoding_output),
  246. (sys.stderr, io_encoding_output)]:
  247. if isinstance(f, file) and (overridden or f.isatty()):
  248. set_file_encoding(f, encoding, errors)
  249. # Order is significant!
  250. sys_flags = (
  251. "debug",
  252. "py3k_warning",
  253. "division_warning",
  254. "division_new",
  255. "inspect",
  256. "interactive",
  257. "optimize",
  258. "dont_write_bytecode",
  259. "no_user_site",
  260. "no_site",
  261. "ignore_environment",
  262. "tabcheck",
  263. "verbose",
  264. "unicode",
  265. "bytes_warning",
  266. "hash_randomization",
  267. )
  268. default_options = dict.fromkeys(
  269. sys_flags +
  270. ("run_command",
  271. "run_module",
  272. "run_stdin",
  273. "warnoptions",
  274. "unbuffered"), 0)
  275. def simple_option(options, name, iterargv):
  276. options[name] += 1
  277. def div_option(options, div, iterargv):
  278. if div == "warn":
  279. options["division_warning"] = 1
  280. elif div == "warnall":
  281. options["division_warning"] = 2
  282. elif div == "new":
  283. options["division_new"] = 1
  284. elif div != "old":
  285. raise CommandLineError("invalid division option: %r" % (div,))
  286. def c_option(options, runcmd, iterargv):
  287. options["run_command"] = runcmd
  288. return ['-c'] + list(iterargv)
  289. def m_option(options, runmodule, iterargv):
  290. options["run_module"] = True
  291. return [runmodule] + list(iterargv)
  292. def W_option(options, warnoption, iterargv):
  293. options["warnoptions"].append(warnoption)
  294. def end_options(options, _, iterargv):
  295. return list(iterargv)
  296. cmdline_options = {
  297. # simple options just increment the counter of the options listed above
  298. 'b': (simple_option, 'bytes_warning'),
  299. 'B': (simple_option, 'dont_write_bytecode'),
  300. 'd': (simple_option, 'debug'),
  301. 'E': (simple_option, 'ignore_environment'),
  302. 'i': (simple_option, 'interactive'),
  303. 'O': (simple_option, 'optimize'),
  304. 'R': (simple_option, 'hash_randomization'),
  305. 's': (simple_option, 'no_user_site'),
  306. 'S': (simple_option, 'no_site'),
  307. 't': (simple_option, 'tabcheck'),
  308. 'U': (simple_option, 'unicode'),
  309. 'u': (simple_option, 'unbuffered'),
  310. 'v': (simple_option, 'verbose'),
  311. '3': (simple_option, 'py3k_warning'),
  312. # more complex options
  313. 'c': (c_option, Ellipsis),
  314. '?': (print_help, None),
  315. 'h': (print_help, None),
  316. '--help': (print_help, None),
  317. 'm': (m_option, Ellipsis),
  318. 'W': (W_option, Ellipsis),
  319. 'V': (print_version, None),
  320. '--version': (print_version, None),
  321. 'Q': (div_option, Ellipsis),
  322. '--info': (print_info, None),
  323. '--jit': (set_jit_option, Ellipsis),
  324. '--': (end_options, None),
  325. }
  326. def handle_argument(c, options, iterargv, iterarg=iter(())):
  327. function, funcarg = cmdline_options[c]
  328. # If needed, fill in the real argument by taking it from the command line
  329. if funcarg is Ellipsis:
  330. remaining = list(iterarg)
  331. if remaining:
  332. funcarg = ''.join(remaining)
  333. else:
  334. try:
  335. funcarg = iterargv.next()
  336. except StopIteration:
  337. if len(c) == 1:
  338. c = '-' + c
  339. raise CommandLineError('Argument expected for the %r option' % c)
  340. return function(options, funcarg, iterargv)
  341. def parse_command_line(argv):
  342. import os
  343. options = default_options.copy()
  344. options['warnoptions'] = []
  345. iterargv = iter(argv)
  346. argv = None
  347. for arg in iterargv:
  348. #
  349. # If the next argument isn't at least two characters long or
  350. # doesn't start with '-', stop processing
  351. if len(arg) < 2 or arg[0] != '-':
  352. if IS_WINDOWS and arg == '/?': # special case
  353. print_help()
  354. argv = [arg] + list(iterargv) # finishes processing
  355. #
  356. # If the next argument is directly in cmdline_options, handle
  357. # it as a single argument
  358. elif arg in cmdline_options:
  359. argv = handle_argument(arg, options, iterargv)
  360. #
  361. # Else interpret the rest of the argument character by character
  362. else:
  363. iterarg = iter(arg)
  364. iterarg.next() # skip the '-'
  365. for c in iterarg:
  366. if c not in cmdline_options:
  367. raise CommandLineError('Unknown option: -%s' % (c,))
  368. argv = handle_argument(c, options, iterargv, iterarg)
  369. if not argv:
  370. argv = ['']
  371. options["run_stdin"] = True
  372. elif argv[0] == '-':
  373. options["run_stdin"] = True
  374. # don't change the list that sys.argv is bound to
  375. # (relevant in case of "reload(sys)")
  376. sys.argv[:] = argv
  377. if not options["ignore_environment"]:
  378. if os.getenv('PYTHONDEBUG'):
  379. options["debug"] = 1
  380. if os.getenv('PYTHONDONTWRITEBYTECODE'):
  381. options["dont_write_bytecode"] = 1
  382. if os.getenv('PYTHONNOUSERSITE'):
  383. options["no_user_site"] = 1
  384. if os.getenv('PYTHONUNBUFFERED'):
  385. options["unbuffered"] = 1
  386. if os.getenv('PYTHONVERBOSE'):
  387. options["verbose"] = 1
  388. if (options["interactive"] or
  389. (not options["ignore_environment"] and os.getenv('PYTHONINSPECT'))):
  390. options["inspect"] = 1
  391. ## We don't print the warning, because it offers no additional security
  392. ## in CPython either (http://bugs.python.org/issue14621)
  393. ## if (options["hash_randomization"] or os.getenv('PYTHONHASHSEED')):
  394. ## print >> sys.stderr, (
  395. ## "Warning: pypy does not implement hash randomization")
  396. if we_are_translated():
  397. flags = [options[flag] for flag in sys_flags]
  398. sys.flags = type(sys.flags)(flags)
  399. sys.py3kwarning = bool(sys.flags.py3k_warning)
  400. sys.dont_write_bytecode = bool(sys.flags.dont_write_bytecode)
  401. if sys.py3kwarning:
  402. print >> sys.stderr, (
  403. "Warning: pypy does not implement py3k warnings")
  404. ## if not we_are_translated():
  405. ## for key in sorted(options):
  406. ## print '%40s: %s' % (key, options[key])
  407. ## print '%40s: %s' % ("sys.argv", sys.argv)
  408. return options
  409. def run_command_line(interactive,
  410. inspect,
  411. run_command,
  412. no_site,
  413. run_module,
  414. run_stdin,
  415. warnoptions,
  416. unbuffered,
  417. ignore_environment,
  418. **ignored):
  419. # with PyPy in top of CPython we can only have around 100
  420. # but we need more in the translated PyPy for the compiler package
  421. if '__pypy__' not in sys.builtin_module_names:
  422. sys.setrecursionlimit(5000)
  423. import os
  424. if unbuffered:
  425. set_unbuffered_io()
  426. elif not sys.stdout.isatty():
  427. set_fully_buffered_io()
  428. mainmodule = type(sys)('__main__')
  429. sys.modules['__main__'] = mainmodule
  430. if not no_site:
  431. try:
  432. import site
  433. except:
  434. print >> sys.stderr, "'import site' failed"
  435. set_stdio_encodings(ignore_environment)
  436. readenv = not ignore_environment
  437. pythonwarnings = readenv and os.getenv('PYTHONWARNINGS')
  438. if pythonwarnings:
  439. warnoptions.extend(pythonwarnings.split(','))
  440. if warnoptions:
  441. sys.warnoptions[:] = warnoptions
  442. from warnings import _processoptions
  443. _processoptions(sys.warnoptions)
  444. # set up the Ctrl-C => KeyboardInterrupt signal handler, if the
  445. # signal module is available
  446. try:
  447. import signal
  448. except ImportError:
  449. pass
  450. else:
  451. signal.signal(signal.SIGINT, signal.default_int_handler)
  452. if hasattr(signal, "SIGPIPE"):
  453. signal.signal(signal.SIGPIPE, signal.SIG_IGN)
  454. if hasattr(signal, 'SIGXFZ'):
  455. signal.signal(signal.SIGXFZ, signal.SIG_IGN)
  456. if hasattr(signal, 'SIGXFSZ'):
  457. signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
  458. def inspect_requested():
  459. # We get an interactive prompt in one of the following three cases:
  460. #
  461. # * interactive=True, from the "-i" option
  462. # or
  463. # * inspect=True and stdin is a tty
  464. # or
  465. # * PYTHONINSPECT is set and stdin is a tty.
  466. #
  467. return (interactive or
  468. ((inspect or (readenv and os.getenv('PYTHONINSPECT')))
  469. and sys.stdin.isatty()))
  470. success = True
  471. try:
  472. if run_command != 0:
  473. # handle the "-c" command
  474. # Put '' on sys.path
  475. sys.path.insert(0, '')
  476. def run_it():
  477. exec run_command in mainmodule.__dict__
  478. success = run_toplevel(run_it)
  479. elif run_module:
  480. # handle the "-m" command
  481. # '' on sys.path is required also here
  482. sys.path.insert(0, '')
  483. import runpy
  484. success = run_toplevel(runpy._run_module_as_main, sys.argv[0])
  485. elif run_stdin:
  486. # handle the case where no command/filename/module is specified
  487. # on the command-line.
  488. # update sys.path *after* loading site.py, in case there is a
  489. # "site.py" file in the script's directory. Only run this if we're
  490. # executing the interactive prompt, if we're running a script we
  491. # put it's directory on sys.path
  492. sys.path.insert(0, '')
  493. if interactive or sys.stdin.isatty():
  494. # If stdin is a tty or if "-i" is specified, we print
  495. # a banner and run $PYTHONSTARTUP.
  496. print_banner(not no_site)
  497. python_startup = readenv and os.getenv('PYTHONSTARTUP')
  498. if python_startup:
  499. try:
  500. f = open(python_startup)
  501. startup = f.read()
  502. f.close()
  503. except IOError, e:
  504. print >> sys.stderr, "Could not open PYTHONSTARTUP"
  505. print >> sys.stderr, "IOError:", e
  506. else:
  507. def run_it():
  508. co_python_startup = compile(startup,
  509. python_startup,
  510. 'exec')
  511. exec co_python_startup in mainmodule.__dict__
  512. mainmodule.__file__ = python_startup
  513. run_toplevel(run_it)
  514. try:
  515. del mainmodule.__file__
  516. except (AttributeError, TypeError):
  517. pass
  518. # Then we need a prompt.
  519. inspect = True
  520. else:
  521. # If not interactive, just read and execute stdin normally.
  522. def run_it():
  523. co_stdin = compile(sys.stdin.read(), '<stdin>', 'exec')
  524. exec co_stdin in mainmodule.__dict__
  525. mainmodule.__file__ = '<stdin>'
  526. success = run_toplevel(run_it)
  527. else:
  528. # handle the common case where a filename is specified
  529. # on the command-line.
  530. filename = sys.argv[0]
  531. mainmodule.__file__ = filename
  532. sys.path.insert(0, sys.pypy_resolvedirof(filename))
  533. # assume it's a pyc file only if its name says so.
  534. # CPython goes to great lengths to detect other cases
  535. # of pyc file format, but I think it's ok not to care.
  536. import imp
  537. if IS_WINDOWS:
  538. filename = filename.lower()
  539. if filename.endswith('.pyc') or filename.endswith('.pyo'):
  540. args = (imp._run_compiled_module, '__main__',
  541. sys.argv[0], None, mainmodule)
  542. else:
  543. # maybe it's the name of a directory or a zip file
  544. filename = sys.argv[0]
  545. importer = imp._getimporter(filename)
  546. if not isinstance(importer, imp.NullImporter):
  547. # yes. put the filename in sys.path[0] and import
  548. # the module __main__
  549. import runpy
  550. sys.path.insert(0, filename)
  551. args = (runpy._run_module_as_main, '__main__', False)
  552. else:
  553. # no. That's the normal path, "pypy stuff.py".
  554. args = (execfile, filename, mainmodule.__dict__)
  555. success = run_toplevel(*args)
  556. except SystemExit, e:
  557. status = e.code
  558. if inspect_requested():
  559. display_exception()
  560. else:
  561. status = not success
  562. # start a prompt if requested
  563. if inspect_requested():
  564. inteactive = False
  565. try:
  566. from _pypy_interact import interactive_console
  567. success = run_toplevel(interactive_console, mainmodule)
  568. except SystemExit, e:
  569. status = e.code
  570. else:
  571. status = not success
  572. return status
  573. def print_banner(copyright):
  574. print 'Python %s on %s' % (sys.version, sys.platform)
  575. if copyright:
  576. print ('Type "help", "copyright", "credits" or '
  577. '"license" for more information.')
  578. STDLIB_WARNING = """\
  579. debug: WARNING: Library path not found, using compiled-in sys.path.
  580. debug: WARNING: 'sys.prefix' will not be set.
  581. debug: WARNING: Make sure the pypy binary is kept inside its tree of files.
  582. debug: WARNING: It is ok to create a symlink to it from somewhere else."""
  583. def setup_bootstrap_path(executable):
  584. """
  585. Try to to as little as possible and to have the stdlib in sys.path. In
  586. particular, we cannot use any unicode at this point, because lots of
  587. unicode operations require to be able to import encodings.
  588. """
  589. # at this point, sys.path is set to the compiled-in one, based on the
  590. # location where pypy was compiled. This is set during the objspace
  591. # initialization by module.sys.state.State.setinitialpath.
  592. #
  593. # Now, we try to find the absolute path of the executable and the stdlib
  594. # path
  595. executable = sys.pypy_find_executable(executable)
  596. stdlib_path = sys.pypy_find_stdlib(executable)
  597. if stdlib_path is None:
  598. print >> sys.stderr, STDLIB_WARNING
  599. else:
  600. sys.path[:] = stdlib_path
  601. # from this point on, we are free to use all the unicode stuff we want,
  602. # This is important for py3k
  603. sys.executable = executable
  604. def entry_point(executable, argv):
  605. # note that before calling setup_bootstrap_path, we are limited because we
  606. # cannot import stdlib modules. In particular, we cannot use unicode
  607. # stuffs (because we need to be able to import encodings) and we cannot
  608. # import os, which is used a bit everywhere in app_main, but only imported
  609. # *after* setup_bootstrap_path
  610. setup_bootstrap_path(executable)
  611. try:
  612. cmdline = parse_command_line(argv)
  613. except CommandLineError, e:
  614. print_error(str(e))
  615. return 2
  616. except SystemExit, e:
  617. return e.code or 0
  618. setup_and_fix_paths(**cmdline)
  619. return run_command_line(**cmdline)
  620. if __name__ == '__main__':
  621. # obscure! try removing the following line, see how it crashes, and
  622. # guess why...
  623. ImStillAroundDontForgetMe = sys.modules['__main__']
  624. # debugging only
  625. def pypy_find_executable(s):
  626. import os
  627. return os.path.abspath(s)
  628. def pypy_find_stdlib(s):
  629. from os.path import abspath, join, dirname as dn
  630. thisfile = abspath(__file__)
  631. root = dn(dn(dn(thisfile)))
  632. return [join(root, 'lib-python', '2'),
  633. join(root, 'lib_pypy')]
  634. def pypy_resolvedirof(s):
  635. # we ignore the issue of symlinks; for tests, the executable is always
  636. # interpreter/app_main.py anyway
  637. import os
  638. return os.path.abspath(os.path.join(s, '..'))
  639. # add an emulator for these pypy-only or 2.7-only functions
  640. # (for test_pyc_commandline_argument)
  641. import imp, runpy
  642. def _run_compiled_module(modulename, filename, file, module):
  643. import os
  644. assert modulename == '__main__'
  645. assert os.path.isfile(filename)
  646. assert filename.endswith('.pyc')
  647. assert file is None
  648. assert module.__name__ == '__main__'
  649. print 'in _run_compiled_module'
  650. def _getimporter(path):
  651. import os, imp
  652. if os.path.isdir(path):
  653. return None
  654. else:
  655. return imp.NullImporter(path)
  656. imp._run_compiled_module = _run_compiled_module
  657. imp._getimporter = _getimporter
  658. import os
  659. reset = []
  660. if 'PYTHONINSPECT_' in os.environ:
  661. reset.append(('PYTHONINSPECT', os.environ.get('PYTHONINSPECT', '')))
  662. os.environ['PYTHONINSPECT'] = os.environ['PYTHONINSPECT_']
  663. if 'PYTHONWARNINGS_' in os.environ:
  664. reset.append(('PYTHONWARNINGS', os.environ.get('PYTHONWARNINGS', '')))
  665. os.environ['PYTHONWARNINGS'] = os.environ['PYTHONWARNINGS_']
  666. del os # make sure that os is not available globally, because this is what
  667. # happens in "real life" outside the tests
  668. if 'time' not in sys.builtin_module_names:
  669. # make some tests happy by loading this before we clobber sys.path
  670. import time; del time
  671. # no one should change to which lists sys.argv and sys.path are bound
  672. old_argv = sys.argv
  673. old_path = sys.path
  674. sys.pypy_find_executable = pypy_find_executable
  675. sys.pypy_find_stdlib = pypy_find_stdlib
  676. sys.pypy_resolvedirof = pypy_resolvedirof
  677. sys.cpython_path = sys.path[:]
  678. try:
  679. sys.exit(int(entry_point(sys.argv[0], sys.argv[1:])))
  680. finally:
  681. # restore the normal prompt (which was changed by _pypy_interact), in
  682. # case we are dropping to CPython's prompt
  683. sys.ps1 = '>>> '
  684. sys.ps2 = '... '
  685. import os; os.environ.update(reset)
  686. assert old_argv is sys.argv
  687. assert old_path is sys.path