PageRenderTime 63ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/translator/goal/app_main.py

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