PageRenderTime 58ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/translator/goal/app_main.py

https://bitbucket.org/quangquach/pypy
Python | 771 lines | 653 code | 57 blank | 61 comment | 104 complexity | 5b05e06f5639622c1d43c518786abc7b MD5 | raw file
  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 = options.items()
  109. optitems.sort()
  110. current = []
  111. for key, value in optitems:
  112. group = key.split('.')
  113. name = group.pop()
  114. n = 0
  115. while n < min(len(current), len(group)) and current[n] == group[n]:
  116. n += 1
  117. while n < len(group):
  118. print '%s[%s]' % (' ' * n, group[n])
  119. n += 1
  120. print '%s%s = %r' % (' ' * n, name, value)
  121. current = group
  122. raise SystemExit
  123. def print_help(*args):
  124. print 'usage: %s [options] [-c cmd|-m mod|file.py|-] [arg...]' % (
  125. sys.executable,)
  126. print __doc__.rstrip()
  127. if 'pypyjit' in sys.builtin_module_names:
  128. print " --jit OPTIONS advanced JIT options: try 'off' or 'help'"
  129. print
  130. raise SystemExit
  131. def _print_jit_help():
  132. try:
  133. import pypyjit
  134. except ImportError:
  135. print >> sys.stderr, "No jit support in %s" % (sys.executable,)
  136. return
  137. items = pypyjit.defaults.items()
  138. items.sort()
  139. print 'Advanced JIT options: a comma-separated list of OPTION=VALUE:'
  140. for key, value in items:
  141. print
  142. print ' %s=N' % (key,)
  143. doc = '%s (default %s)' % (pypyjit.PARAMETER_DOCS[key], value)
  144. while len(doc) > 72:
  145. i = doc[:74].rfind(' ')
  146. if i < 0:
  147. i = doc.find(' ')
  148. if i < 0:
  149. i = len(doc)
  150. print ' ' + doc[:i]
  151. doc = doc[i+1:]
  152. print ' ' + doc
  153. print
  154. print ' off'
  155. print ' turn off the JIT'
  156. print ' help'
  157. print ' print this page'
  158. def print_version(*args):
  159. print >> sys.stderr, "Python", sys.version
  160. raise SystemExit
  161. def set_jit_option(options, jitparam, *args):
  162. if jitparam == 'help':
  163. _print_jit_help()
  164. raise SystemExit
  165. if 'pypyjit' not in sys.builtin_module_names:
  166. print >> sys.stderr, ("Warning: No jit support in %s" %
  167. (sys.executable,))
  168. else:
  169. import pypyjit
  170. pypyjit.set_param(jitparam)
  171. class CommandLineError(Exception):
  172. pass
  173. def print_error(msg):
  174. print >> sys.stderr, msg
  175. print >> sys.stderr, 'usage: %s [options]' % (sys.executable,)
  176. print >> sys.stderr, 'Try `%s -h` for more information.' % (sys.executable,)
  177. def fdopen(fd, mode, bufsize=-1):
  178. try:
  179. fdopen = file.fdopen
  180. except AttributeError: # only on top of CPython, running tests
  181. from os import fdopen
  182. return fdopen(fd, mode, bufsize)
  183. def set_unbuffered_io():
  184. sys.stdin = sys.__stdin__ = fdopen(0, 'rb', 0)
  185. sys.stdout = sys.__stdout__ = fdopen(1, 'wb', 0)
  186. sys.stderr = sys.__stderr__ = fdopen(2, 'wb', 0)
  187. def set_fully_buffered_io():
  188. sys.stdout = sys.__stdout__ = fdopen(1, 'w')
  189. # ____________________________________________________________
  190. # Main entry point
  191. def we_are_translated():
  192. # app-level, very different from pypy.rlib.objectmodel.we_are_translated
  193. return hasattr(sys, 'pypy_translation_info')
  194. if 'nt' in sys.builtin_module_names:
  195. IS_WINDOWS = True
  196. else:
  197. IS_WINDOWS = False
  198. def setup_and_fix_paths(ignore_environment=False, **extra):
  199. import os
  200. newpath = sys.path[:]
  201. del sys.path[:]
  202. # first prepend PYTHONPATH
  203. readenv = not ignore_environment
  204. path = readenv and os.getenv('PYTHONPATH')
  205. if path:
  206. sys.path.extend(path.split(os.pathsep))
  207. # then add again the original entries, ignoring duplicates
  208. _seen = set()
  209. for dir in newpath:
  210. if dir not in _seen:
  211. sys.path.append(dir)
  212. _seen.add(dir)
  213. def set_stdio_encodings(ignore_environment):
  214. import os
  215. readenv = not ignore_environment
  216. io_encoding = readenv and os.getenv("PYTHONIOENCODING")
  217. if io_encoding:
  218. errors = None
  219. if ":" in io_encoding:
  220. io_encoding, errors = io_encoding.split(":", 1)
  221. set_io_encoding(io_encoding, io_encoding, errors, True)
  222. else:
  223. if IS_WINDOWS:
  224. import __pypy__
  225. io_encoding, io_encoding_output = __pypy__.get_console_cp()
  226. else:
  227. io_encoding = io_encoding_output = sys.getfilesystemencoding()
  228. if io_encoding:
  229. set_io_encoding(io_encoding, io_encoding_output, None, False)
  230. def set_io_encoding(io_encoding, io_encoding_output, errors, overridden):
  231. try:
  232. import _file
  233. except ImportError:
  234. if sys.version_info < (2, 7):
  235. return
  236. # HACK: while running on top of CPython, and make sure to import
  237. # CPython's ctypes (because at this point sys.path has already been
  238. # set to the pypy one)
  239. pypy_path = sys.path
  240. try:
  241. sys.path = sys.cpython_path
  242. import ctypes
  243. finally:
  244. sys.path = pypy_path
  245. set_file_encoding = ctypes.pythonapi.PyFile_SetEncodingAndErrors
  246. set_file_encoding.argtypes = [ctypes.py_object, ctypes.c_char_p, ctypes.c_char_p]
  247. else:
  248. set_file_encoding = _file.set_file_encoding
  249. for f, encoding in [(sys.stdin, io_encoding),
  250. (sys.stdout, io_encoding_output),
  251. (sys.stderr, io_encoding_output)]:
  252. if isinstance(f, file) and (overridden or f.isatty()):
  253. set_file_encoding(f, encoding, errors)
  254. # Order is significant!
  255. sys_flags = (
  256. "debug",
  257. "py3k_warning",
  258. "division_warning",
  259. "division_new",
  260. "inspect",
  261. "interactive",
  262. "optimize",
  263. "dont_write_bytecode",
  264. "no_user_site",
  265. "no_site",
  266. "ignore_environment",
  267. "tabcheck",
  268. "verbose",
  269. "unicode",
  270. "bytes_warning",
  271. "hash_randomization",
  272. )
  273. default_options = dict.fromkeys(
  274. sys_flags +
  275. ("run_command",
  276. "run_module",
  277. "run_stdin",
  278. "warnoptions",
  279. "unbuffered"), 0)
  280. PYTHON26 = True
  281. def simple_option(options, name, iterargv):
  282. options[name] += 1
  283. def div_option(options, div, iterargv):
  284. if div == "warn":
  285. options["division_warning"] = 1
  286. elif div == "warnall":
  287. options["division_warning"] = 2
  288. elif div == "new":
  289. options["division_new"] = 1
  290. elif div != "old":
  291. raise CommandLineError("invalid division option: %r" % (div,))
  292. def c_option(options, runcmd, iterargv):
  293. options["run_command"] = runcmd
  294. return ['-c'] + list(iterargv)
  295. def m_option(options, runmodule, iterargv):
  296. options["run_module"] = True
  297. return [runmodule] + list(iterargv)
  298. def W_option(options, warnoption, iterargv):
  299. options["warnoptions"].append(warnoption)
  300. def end_options(options, _, iterargv):
  301. return list(iterargv)
  302. cmdline_options = {
  303. # simple options just increment the counter of the options listed above
  304. 'd': (simple_option, 'debug'),
  305. 'i': (simple_option, 'interactive'),
  306. 'O': (simple_option, 'optimize'),
  307. 'S': (simple_option, 'no_site'),
  308. 'E': (simple_option, 'ignore_environment'),
  309. 't': (simple_option, 'tabcheck'),
  310. 'v': (simple_option, 'verbose'),
  311. 'U': (simple_option, 'unicode'),
  312. 'u': (simple_option, 'unbuffered'),
  313. # more complex options
  314. 'Q': (div_option, Ellipsis),
  315. 'c': (c_option, Ellipsis),
  316. 'm': (m_option, Ellipsis),
  317. 'W': (W_option, Ellipsis),
  318. 'V': (print_version, None),
  319. '--version': (print_version, None),
  320. '--info': (print_info, None),
  321. 'h': (print_help, None),
  322. '--help': (print_help, None),
  323. '--jit': (set_jit_option, Ellipsis),
  324. '--': (end_options, None),
  325. }
  326. if PYTHON26:
  327. cmdline_options.update({
  328. '3': (simple_option, 'py3k_warning'),
  329. 'B': (simple_option, 'dont_write_bytecode'),
  330. 's': (simple_option, 'no_user_site'),
  331. 'b': (simple_option, 'bytes_warning'),
  332. 'R': (simple_option, 'hash_randomization'),
  333. })
  334. def handle_argument(c, options, iterargv, iterarg=iter(())):
  335. function, funcarg = cmdline_options[c]
  336. #
  337. # If needed, fill in the real argument by taking it from the command line
  338. if funcarg is Ellipsis:
  339. remaining = list(iterarg)
  340. if remaining:
  341. funcarg = ''.join(remaining)
  342. else:
  343. try:
  344. funcarg = iterargv.next()
  345. except StopIteration:
  346. if len(c) == 1:
  347. c = '-' + c
  348. raise CommandLineError('Argument expected for the %r option' % c)
  349. #
  350. return function(options, funcarg, iterargv)
  351. def parse_command_line(argv):
  352. import os
  353. options = default_options.copy()
  354. options['warnoptions'] = []
  355. #
  356. iterargv = iter(argv)
  357. argv = None
  358. for arg in iterargv:
  359. #
  360. # If the next argument isn't at least two characters long or
  361. # doesn't start with '-', stop processing
  362. if len(arg) < 2 or arg[0] != '-':
  363. if IS_WINDOWS and arg == '/?': # special case
  364. print_help()
  365. argv = [arg] + list(iterargv) # finishes processing
  366. #
  367. # If the next argument is directly in cmdline_options, handle
  368. # it as a single argument
  369. elif arg in cmdline_options:
  370. argv = handle_argument(arg, options, iterargv)
  371. #
  372. # Else interpret the rest of the argument character by character
  373. else:
  374. iterarg = iter(arg)
  375. iterarg.next() # skip the '-'
  376. for c in iterarg:
  377. if c not in cmdline_options:
  378. raise CommandLineError('Unknown option: -%s' % (c,))
  379. argv = handle_argument(c, options, iterargv, iterarg)
  380. if not argv:
  381. argv = ['']
  382. options["run_stdin"] = True
  383. elif argv[0] == '-':
  384. options["run_stdin"] = True
  385. # don't change the list that sys.argv is bound to
  386. # (relevant in case of "reload(sys)")
  387. sys.argv[:] = argv
  388. if PYTHON26 and not options["ignore_environment"]:
  389. if os.getenv('PYTHONNOUSERSITE'):
  390. options["no_user_site"] = 1
  391. if os.getenv('PYTHONDONTWRITEBYTECODE'):
  392. options["dont_write_bytecode"] = 1
  393. if (options["interactive"] or
  394. (not options["ignore_environment"] and os.getenv('PYTHONINSPECT'))):
  395. options["inspect"] = 1
  396. ## We don't print the warning, because it offers no additional security
  397. ## in CPython either (http://bugs.python.org/issue14621)
  398. ## if (options["hash_randomization"] or os.getenv('PYTHONHASHSEED')):
  399. ## print >> sys.stderr, (
  400. ## "Warning: pypy does not implement hash randomization")
  401. if PYTHON26 and we_are_translated():
  402. flags = [options[flag] for flag in sys_flags]
  403. sys.flags = type(sys.flags)(flags)
  404. sys.py3kwarning = bool(sys.flags.py3k_warning)
  405. sys.dont_write_bytecode = bool(sys.flags.dont_write_bytecode)
  406. if sys.py3kwarning:
  407. print >> sys.stderr, (
  408. "Warning: pypy does not implement py3k warnings")
  409. ## if not we_are_translated():
  410. ## for key in sorted(options):
  411. ## print '%40s: %s' % (key, options[key])
  412. ## print '%40s: %s' % ("sys.argv", sys.argv)
  413. return options
  414. def run_command_line(interactive,
  415. inspect,
  416. run_command,
  417. no_site,
  418. run_module,
  419. run_stdin,
  420. warnoptions,
  421. unbuffered,
  422. ignore_environment,
  423. **ignored):
  424. # with PyPy in top of CPython we can only have around 100
  425. # but we need more in the translated PyPy for the compiler package
  426. if '__pypy__' not in sys.builtin_module_names:
  427. sys.setrecursionlimit(5000)
  428. import os
  429. if unbuffered:
  430. set_unbuffered_io()
  431. elif not sys.stdout.isatty():
  432. set_fully_buffered_io()
  433. mainmodule = type(sys)('__main__')
  434. sys.modules['__main__'] = mainmodule
  435. if not no_site:
  436. try:
  437. import site
  438. except:
  439. print >> sys.stderr, "'import site' failed"
  440. set_stdio_encodings(ignore_environment)
  441. readenv = not ignore_environment
  442. pythonwarnings = readenv and os.getenv('PYTHONWARNINGS')
  443. if pythonwarnings:
  444. warnoptions.extend(pythonwarnings.split(','))
  445. if warnoptions:
  446. sys.warnoptions[:] = warnoptions
  447. from warnings import _processoptions
  448. _processoptions(sys.warnoptions)
  449. # set up the Ctrl-C => KeyboardInterrupt signal handler, if the
  450. # signal module is available
  451. try:
  452. import signal
  453. except ImportError:
  454. pass
  455. else:
  456. signal.signal(signal.SIGINT, signal.default_int_handler)
  457. if hasattr(signal, "SIGPIPE"):
  458. signal.signal(signal.SIGPIPE, signal.SIG_IGN)
  459. if hasattr(signal, 'SIGXFZ'):
  460. signal.signal(signal.SIGXFZ, signal.SIG_IGN)
  461. if hasattr(signal, 'SIGXFSZ'):
  462. signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
  463. def inspect_requested():
  464. # We get an interactive prompt in one of the following three cases:
  465. #
  466. # * interactive=True, from the "-i" option
  467. # or
  468. # * inspect=True and stdin is a tty
  469. # or
  470. # * PYTHONINSPECT is set and stdin is a tty.
  471. #
  472. return (interactive or
  473. ((inspect or (readenv and os.getenv('PYTHONINSPECT')))
  474. and sys.stdin.isatty()))
  475. success = True
  476. try:
  477. if run_command != 0:
  478. # handle the "-c" command
  479. # Put '' on sys.path
  480. sys.path.insert(0, '')
  481. def run_it():
  482. exec run_command in mainmodule.__dict__
  483. success = run_toplevel(run_it)
  484. elif run_module:
  485. # handle the "-m" command
  486. # '' on sys.path is required also here
  487. sys.path.insert(0, '')
  488. import runpy
  489. success = run_toplevel(runpy._run_module_as_main, sys.argv[0])
  490. elif run_stdin:
  491. # handle the case where no command/filename/module is specified
  492. # on the command-line.
  493. # update sys.path *after* loading site.py, in case there is a
  494. # "site.py" file in the script's directory. Only run this if we're
  495. # executing the interactive prompt, if we're running a script we
  496. # put it's directory on sys.path
  497. sys.path.insert(0, '')
  498. if interactive or sys.stdin.isatty():
  499. # If stdin is a tty or if "-i" is specified, we print
  500. # a banner and run $PYTHONSTARTUP.
  501. print_banner()
  502. python_startup = readenv and os.getenv('PYTHONSTARTUP')
  503. if python_startup:
  504. try:
  505. f = open(python_startup)
  506. startup = f.read()
  507. f.close()
  508. except IOError, e:
  509. print >> sys.stderr, "Could not open PYTHONSTARTUP"
  510. print >> sys.stderr, "IOError:", e
  511. else:
  512. def run_it():
  513. co_python_startup = compile(startup,
  514. python_startup,
  515. 'exec')
  516. exec co_python_startup in mainmodule.__dict__
  517. run_toplevel(run_it)
  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():
  574. print 'Python %s on %s' % (sys.version, sys.platform)
  575. print ('Type "help", "copyright", "credits" or '
  576. '"license" for more information.')
  577. STDLIB_WARNING = """\
  578. debug: WARNING: Library path not found, using compiled-in sys.path.
  579. debug: WARNING: 'sys.prefix' will not be set.
  580. debug: WARNING: Make sure the pypy binary is kept inside its tree of files.
  581. debug: WARNING: It is ok to create a symlink to it from somewhere else."""
  582. def setup_bootstrap_path(executable):
  583. """
  584. Try to to as little as possible and to have the stdlib in sys.path. In
  585. particular, we cannot use any unicode at this point, because lots of
  586. unicode operations require to be able to import encodings.
  587. """
  588. # at this point, sys.path is set to the compiled-in one, based on the
  589. # location where pypy was compiled. This is set during the objspace
  590. # initialization by module.sys.state.State.setinitialpath.
  591. #
  592. # Now, we try to find the absolute path of the executable and the stdlib
  593. # path
  594. executable = sys.pypy_find_executable(executable)
  595. stdlib_path = sys.pypy_find_stdlib(executable)
  596. if stdlib_path is None:
  597. print >> sys.stderr, STDLIB_WARNING
  598. else:
  599. sys.path[:] = stdlib_path
  600. # from this point on, we are free to use all the unicode stuff we want,
  601. # This is important for py3k
  602. sys.executable = executable
  603. def entry_point(executable, argv):
  604. # note that before calling setup_bootstrap_path, we are limited because we
  605. # cannot import stdlib modules. In particular, we cannot use unicode
  606. # stuffs (because we need to be able to import encodings) and we cannot
  607. # import os, which is used a bit everywhere in app_main, but only imported
  608. # *after* setup_bootstrap_path
  609. setup_bootstrap_path(executable)
  610. try:
  611. cmdline = parse_command_line(argv)
  612. except CommandLineError, e:
  613. print_error(str(e))
  614. return 2
  615. except SystemExit, e:
  616. return e.code or 0
  617. setup_and_fix_paths(**cmdline)
  618. return run_command_line(**cmdline)
  619. if __name__ == '__main__':
  620. # obscure! try removing the following line, see how it crashes, and
  621. # guess why...
  622. ImStillAroundDontForgetMe = sys.modules['__main__']
  623. # debugging only
  624. def pypy_find_executable(s):
  625. import os
  626. return os.path.abspath(s)
  627. def pypy_find_stdlib(s):
  628. from os.path import abspath, join, dirname as dn
  629. thisfile = abspath(__file__)
  630. root = dn(dn(dn(dn(thisfile))))
  631. return [join(root, 'lib-python', '2.7'),
  632. join(root, 'lib_pypy')]
  633. def pypy_resolvedirof(s):
  634. # we ignore the issue of symlinks; for tests, the executable is always
  635. # translator/goal/app_main.py anyway
  636. import os
  637. return os.path.abspath(os.path.join(s, '..'))
  638. # add an emulator for these pypy-only or 2.7-only functions
  639. # (for test_pyc_commandline_argument)
  640. import imp, runpy
  641. def _run_compiled_module(modulename, filename, file, module):
  642. import os
  643. assert modulename == '__main__'
  644. assert os.path.isfile(filename)
  645. assert filename.endswith('.pyc')
  646. assert file is None
  647. assert module.__name__ == '__main__'
  648. print 'in _run_compiled_module'
  649. def _getimporter(path):
  650. import os, imp
  651. if os.path.isdir(path):
  652. return None
  653. else:
  654. return imp.NullImporter(path)
  655. imp._run_compiled_module = _run_compiled_module
  656. imp._getimporter = _getimporter
  657. import os
  658. reset = []
  659. if 'PYTHONINSPECT_' in os.environ:
  660. reset.append(('PYTHONINSPECT', os.environ.get('PYTHONINSPECT', '')))
  661. os.environ['PYTHONINSPECT'] = os.environ['PYTHONINSPECT_']
  662. if 'PYTHONWARNINGS_' in os.environ:
  663. reset.append(('PYTHONWARNINGS', os.environ.get('PYTHONWARNINGS', '')))
  664. os.environ['PYTHONWARNINGS'] = os.environ['PYTHONWARNINGS_']
  665. del os # make sure that os is not available globally, because this is what
  666. # happens in "real life" outside the tests
  667. # no one should change to which lists sys.argv and sys.path are bound
  668. old_argv = sys.argv
  669. old_path = sys.path
  670. sys.pypy_find_executable = pypy_find_executable
  671. sys.pypy_find_stdlib = pypy_find_stdlib
  672. sys.pypy_resolvedirof = pypy_resolvedirof
  673. sys.cpython_path = sys.path[:]
  674. try:
  675. sys.exit(int(entry_point(sys.argv[0], sys.argv[1:])))
  676. finally:
  677. # restore the normal prompt (which was changed by _pypy_interact), in
  678. # case we are dropping to CPython's prompt
  679. sys.ps1 = '>>> '
  680. sys.ps2 = '... '
  681. import os; os.environ.update(reset)
  682. assert old_argv is sys.argv
  683. assert old_path is sys.path