1. 27 Nov, 2020 1 commit
  2. 26 Nov, 2020 7 commits
    • Kirill Smelkov's avatar
      gpython: Implement -O · 8564dfdd
      Kirill Smelkov authored
      Let's teach gpython and pymain about -O because buildout calls `python -O`
      to byte-compile python sources in optimized mode:
      
      slapos!862 (comment 121470)
      
      When seeing -O, we take the approach to reexecute underlying python with
      -O, so that e.g.
      
      	gpython -O file.py
      
      becomes executed as
      
      	python -O gpython file.py
      
      This ensures correctness. The same approach could be used to implement
      support for e.g. -S and other low-level options.
      
      An earlier attempt to implement -O without reexecution can be seen at
      
      !7
      
      together with list of problems that arise via that way.
      
      Original idea to reexecute itself come from @jerome.
      8564dfdd
    • Kirill Smelkov's avatar
      gpython: Fix crash when invoked as e.g. ./bin/gpython · 076cdd8f
      Kirill Smelkov authored
      There was an assert because sys.path[0] is setup as realpath (real, not
      relative), but if exe was given as relative path it was raising like
      below:
      
          gpython/gpython_test.py::test_pymain_run_via_relpath GPython 0.0.7.post1 [gevent 20.9.0] / CPython 3.8.6
          Traceback (most recent call last):
            File "./__init__.py", line 482, in <module>
              main()
            File "./__init__.py", line 366, in main
              pymain(argv, init)
            File "./__init__.py", line 82, in pymain
              raise RuntimeError('pymain: internal error: sys.path[0] was not set by underlying python to dirname(exe):'
          RuntimeError: pymain: internal error: sys.path[0] was not set by underlying python to dirname(exe):
      
                  exe:    ./__init__.py
                  sys.path[0]:    /home/kirr/src/tools/go/pygolang-master/gpython
          FAILED
      
      -> Fix it by setting up exe as realpath.
      076cdd8f
    • Kirill Smelkov's avatar
      gpython: Move sys.executable setup from main to pymain · 11b367c6
      Kirill Smelkov authored
      This is generic step and should be done under both gpython and standard
      python. Handling sys.executable inside pymain offloads users from
      setting up sys.executable by themselves, e.g. as in here:
      
      https://lab.nexedi.com/nexedi/slapos/blob/46ed2afe/component/pygolang/buildout.cfg#L39-43
      11b367c6
    • Kirill Smelkov's avatar
      gpython: Rework pymain interface to accept python exe as argv[0] · 21756bd3
      Kirill Smelkov authored
      In other words pymain now requires to be passed in full argv when
      called. We will need exe=argv[0] in a followup patch to be able to
      reexecute underlying python interpreter when given options like -O, -S,
      etc...
      
      This is change in behaviour and in general must come with changing
      pymain name - e.g. to pymain2 - so that old pymain continues to work as
      before. However since there are not so many known pymain users, we can
      probably do this change in place since we'll care ourselves about all
      those users:
      
      - [python-interpreter] in SlapOS:
        https://lab.nexedi.com/nexedi/slapos/blob/46ed2afe/component/pygolang/buildout.cfg#L30-53
      
      - pyruntraced in Go123:
        https://lab.nexedi.com/kirr/go123/blob/96046edf/tracing/cmd/pyruntraced
      
      - zobjtrace in ZODB:
        https://lab.nexedi.com/kirr/ZODB/blob/07c21671/zobjtrace
      
      So I hope it is ok.
      21756bd3
    • Kirill Smelkov's avatar
      gpython: Factor-out options parsing into getopt-style _IGetOpt helper · 26058b5b
      Kirill Smelkov authored
      Python allows multiple single-letter options and their arguments to be
      coming on single argument, for example:
      
      	python -OQc'print 1'
      	python -OQc 'print 1'
      	python -OQ -c 'print 1'
      	etc...
      
      We are currently trying to handle that at every option, but even though
      it kind of works, it is limited and will break once we will start adding
      options.
      
      -> Refactor options parsing into getopt-style helper. We cannot use
      getopt itself because it will complain e.g. on `gpython file.py
      --my-custom-opt` that my-custom-opt is unexpected.
      26058b5b
    • Jérome Perrin's avatar
      gpython: tests: check command executed with -c do not use print function on PY2 · 167912d3
      Jérome Perrin authored
      follow up of 64088e8a (gpython: Don't inherit __future__ when executing
      scripts, 2020-11-26)
      
      /reviewed-by @kirr
      /reviewed-on !9
      167912d3
    • Jérome Perrin's avatar
      gpython: Don't inherit __future__ when executing scripts · 64088e8a
      Jérome Perrin authored
      Because we use execfile to emulate "python script.py" invocation, future
      enabled in gpython main script are also enabled in "script.py" and because
      we use print_function feature, it was also applied in "script.py".
      On python 2 when "script.py" uses print statements they were considered as
      SyntaxError.
      
      Hopefuly, compile has a `dont_inherit` flag which does exactly what we need
      here: compile the script without inheriting futures enabled, so we use
      compile with this flag.
      
      /reviewed-by @kirr
      /reviewed-on !8
      64088e8a
  3. 14 Oct, 2020 2 commits
    • Kirill Smelkov's avatar
      gpython: tests: Skip test_pymain_syspath on SlapOS · 0fa9d6e7
      Kirill Smelkov authored
      With buildout raw underlying python interpreter does not have access to
      eggs with which gpython script was generated. See previous commit for
      details.
      0fa9d6e7
    • Kirill Smelkov's avatar
      gpython: Detect buildout and don't expect exedir to be on sys.path[0] in that case · 92bb5bcc
      Kirill Smelkov authored
      When buildout generates scripts, it injects the following prologue for
      them:
      
         #!/path/to/underlying/python
      
         import sys
         sys.path[0:0] = [
           'path/to/egg1',
           'path/to/egg2',
           ...
         ]
      
         import SCRIPT
         SCRIPT.main()
      
      This way path to eggs are inserted before what was originally
      sys.path[0] and it breaks gpython check that `sys.path[0] == exedir`.
      
      -> Fix it by detecting buildout and in that case verifying that exedir
      is only present in sys.path, not located in sys.path[0].
      92bb5bcc
  4. 22 Sep, 2020 4 commits
    • Kirill Smelkov's avatar
      gpython: Fix pymain to properly setup sys.path (take 2) · fb98e594
      Kirill Smelkov authored
      This continues 6b4990f6 (gpython: Fix pymain to properly setup
      sys.path[0]) - now we add test and verify that gpython actually sets
      sys.path in the same way as underlying python does:
      
      - don't add directory of gpython to sys.path
      - for `gpython file` add to sys.path[0] realpath(dir(file)) instead of
        dir(file)  (see PySys_SetArgvEx for the reference, and else - if we do
        not make this change - added test breaks)
      - for `gpython -m mod` add to sys.path[0] realpath('') instead of ''.
        This exactly matches PY3 behaviour, while PY2 behaviour is to add ''
        However PY3 behaviour
      
          * is more sane, and
          * fixes test_defer_excchain_traceback on py27-gevent
      
        -> so we stick to it.
      
      Now all tests pass again.
      fb98e594
    • Kirill Smelkov's avatar
      gpython: Preimport golang and gevent from exactly the same place as std python would do · 1f6f31cd
      Kirill Smelkov authored
      GPython preimports golang and gevent, but until now, it was preimporting
      them before adjusting sys.path according to given -c/-m/file/... And
      this was leading to difference in behaviour with standard Python where
      e.g. `import golang` might result in different files loaded if e.g.
      golang/ is there on cwd and -c/-m was given.
      
      -> Rework gpython startup so that golang/gevent preimport happens after
      sys.path initialization.
      
      This fixes `tox -e py27-gevent` which was previously failing on
      test_defer_excchain_dump_pytest / test_defer_excchain_dump_ipython
      because dumped paths were different than expected ones.
      
      It, however, breaks test_defer_excchain_traceback on py27-gevent.  ->
      We'll do more fixups to sys.path handling in the next patch which will
      fix that failure as well.
      1f6f31cd
    • Kirill Smelkov's avatar
      gpython: Move code to handle -V to "start interpreter" phase · 51925488
      Kirill Smelkov authored
      We'll need this in the next patch, where golang/gevent preimport will be
      moved from "before call to pymain", to "in between option parsing and
      interpreter start".
      51925488
    • Kirill Smelkov's avatar
      gpython: Implement -W · a0016938
      Kirill Smelkov authored
      We'll need warnings control in the next patch to fix Pytest integration
      wrt python3-dbg with `-W ignore::DeprecationWarning`.
      a0016938
  5. 21 Sep, 2020 1 commit
    • Kirill Smelkov's avatar
      gpython: Reorganize options parsing · b47edf42
      Kirill Smelkov authored
      Reorganize parsiong of command line options so that first all options are
      parsed in a loop, and only after that a module/file/command is executed.
      
      This is needed as preparatory step for next patch: there we'll add
      support for -W, and `-W arg` can be given multiple times and has to be
      processed multiple times by creating multiple corresponding warning
      filters. Because those warning filters has to be applied uniformly to
      all 4 codepaths of execution phase (-m/-c/file/interactive console), it
      makes sense to move execution phase to after options parsing and inject
      common runtime preparatory steps right before that.
      
      This logic generally applies not only to -W, but to all other python
      options - e.g. -Q,-u,...
      b47edf42
  6. 30 Jul, 2020 4 commits
    • Kirill Smelkov's avatar
      gpython: Add way to run it with threads runtime · a6b993c8
      Kirill Smelkov authored
      Until now gpython was always activating gevent on startup + adding
      goodness such as "always UTF-8 default encoding"; go, chan, b/u and
      friends available from builtin namespace, etc... While those goodness
      are sometimes useful on their own, it is not always appropriate to force
      a project to switch from threads to gevent.
      
      For this reason add a flag to select which runtime - either gevent
      or threads - gpython should use.
      
      	gpython -Xgpython.runtime=gevent	selects gevent,
      
      while
      
      	gpython -Xgpython.runtime=threads	selects threads.
      
      Gevent remains the default.
      
      It is also possible to specify desired runtime via $GPYTHON_RUNTIME
      environment variable.
      
      /reviewed-on !5
      a6b993c8
    • Kirill Smelkov's avatar
      gpython: Reorganize main a bit · c0282565
      Kirill Smelkov authored
      Restructure code a bit to prepare it for the next patch.
      Plain code movement.
      
      /reviewed-on !5
      c0282565
    • Kirill Smelkov's avatar
      gpython: Add support for -V / --version · 70c4c82f
      Kirill Smelkov authored
      On CPython:
      
      	$ python -V
      	Python 2.7.18
      
      	$ gpython -V
      	GPython 0.0.6.post2 [gevent 20.6.2] / CPython 2.7.18
      
      On PyPy:
      
      	$ python -V
              Python 3.6.9 (2ad108f17bdb, Apr 07 2020, 02:59:05)
              [PyPy 7.3.1 with GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]
      
      	$ gpython -V
      	GPython 0.0.6.post2 [gevent 20.5.0] / PyPy 7.3.1 / Python 3.6.9
      
      /reviewed-on !5
      70c4c82f
    • Kirill Smelkov's avatar
      gpython: Support -c<command>, not only -c <command> · e6714e49
      Kirill Smelkov authored
      And same for -m<module> - becuase Python supports it this way.
      
      Before the patch:
      
      	$ python '-cprint "hello world"'
      	hello world
      	$ gpython '-cprint "hello world"'
      	unknown option: '-cprint "hello world"'
      
      After the patch:
      
      	$ python '-cprint "hello world"'
      	hello world
      	$ gpython '-cprint "hello world"'
      	hello world
      
      /reviewed-on !5
      e6714e49
  7. 07 Jul, 2020 1 commit
    • Kirill Smelkov's avatar
      gpython: CPython3.8 always imports time via zipimport hook · 1f184095
      Kirill Smelkov authored
      	kirr@deco:~$ python3.8 -v
      	import _frozen_importlib # frozen
      	import _imp # builtin
      	import '_thread' # <class '_frozen_importlib.BuiltinImporter'>
      	import '_warnings' # <class '_frozen_importlib.BuiltinImporter'>
      	import '_weakref' # <class '_frozen_importlib.BuiltinImporter'>
      	import '_frozen_importlib_external' # <class '_frozen_importlib.FrozenImporter'>
      	import '_io' # <class '_frozen_importlib.BuiltinImporter'>
      	import 'marshal' # <class '_frozen_importlib.BuiltinImporter'>
      	import 'posix' # <class '_frozen_importlib.BuiltinImporter'>
      	import _thread # previously loaded ('_thread')
      	import '_thread' # <class '_frozen_importlib.BuiltinImporter'>
      	import _weakref # previously loaded ('_weakref')
      	import '_weakref' # <class '_frozen_importlib.BuiltinImporter'>
      	# installing zipimport hook
      	import 'time' # <class '_frozen_importlib.BuiltinImporter'>		<-- NOTE
      	import 'zipimport' # <class '_frozen_importlib.FrozenImporter'>
      	# installed zipimport hook
      
      See https://github.com/python/cpython/commit/79d1c2e6c9d1 for details
      (`import time` in zipimport.py)
      1f184095
  8. 29 May, 2020 1 commit
    • Kirill Smelkov's avatar
      gpython: Include gevent version into banner · 0e3da017
      Kirill Smelkov authored
      Gevent is major component gpython builds on - it deserves to be included
      into version and is handy to know if one hits a bug with gpython - to
      see in which particular runtime environment the bug was hit.
      
      Before:
      
          $ gpython
          Python 3.7.3 (default, Dec 20 2019, 18:57:59)
          [GCC 8.3.0] [GPython 0.0.6.post2] on linux
          Type "help", "copyright", "credits" or "license" for more information.
          (InteractiveConsole)
          >>>
      
      After:
      
          $ gpython
          Python 3.7.3 (default, Dec 20 2019, 18:57:59)
          [GCC 8.3.0] [GPython 0.0.6.post2] [gevent 20.5.1] on linux
          Type "help", "copyright", "credits" or "license" for more information.
          (InteractiveConsole)
          >>>
      
      /cc @gabriel, @jerome
      /proposed-for-review-on: !4
      0e3da017
  9. 10 Feb, 2020 1 commit
    • Kirill Smelkov's avatar
      golang: Expose error at Py level · 17798442
      Kirill Smelkov authored
      The first step to expose errors and error chaining to Python:
      
      - Add pyerror that wraps a pyx/nogil C-level error and is exposed as golang.error at py level.
      - py errors must be compared by ==, not by "is"
      - Add (py) errors.New to create a new error from text.
      - a C-level error that has .Unwrap, is exposed with .Unwrap at py level,
        but full py-level chaining will be implemented in a follow-up patch.
      - py error does not support inheritance yet.
      
      Top-level documentation is TODO.
      17798442
  10. 04 Feb, 2020 1 commit
    • Kirill Smelkov's avatar
      golang: Provide b, u for strings · bcb95cd5
      Kirill Smelkov authored
      With Python3 I've got tired to constantly use .encode() and .decode();
      getting exception if original argument was unicode on e.g. b.decode();
      getting exception on raw bytes that are invalid UTF-8, not being able to
      use bytes literal with non-ASCII characters, etc.
      
      So instead of this pain provide two functions that make sure an object
      is either bytes or unicode:
      
      - b converts str/unicode/bytes s to UTF-8 encoded bytestring.
      
      	Bytes input is preserved as-is:
      
      	   b(bytes_input) == bytes_input
      
      	Unicode input is UTF-8 encoded. The encoding always succeeds.
      	b is reverse operation to u - the following invariant is always true:
      
      	   b(u(bytes_input)) == bytes_input
      
      - u converts str/unicode/bytes s to unicode string.
      
      	Unicode input is preserved as-is:
      
      	   u(unicode_input) == unicode_input
      
      	Bytes input is UTF-8 decoded. The decoding always succeeds and input
      	information is not lost: non-valid UTF-8 bytes are decoded into
      	surrogate codes ranging from U+DC80 to U+DCFF.
      	u is reverse operation to b - the following invariant is always true:
      
      	   u(b(unicode_input)) == unicode_input
      
      NOTE: encoding _and_ decoding *never* fail nor loose information. This
      is achieved by using 'surrogateescape' error handler on Python3, and
      providing manual fallback that behaves the same way on Python2.
      
      The naming is chosen with the idea so that b(something) resembles
      b"something", and u(something) resembles u"something".
      
      This, even being only a part of strings solution discussed in [1],
      should help handle byte- and unicode- strings in more robust and
      distraction free way.
      
      Top-level documentation is TODO.
      
      [1] zodbtools!13
      bcb95cd5
  11. 03 Oct, 2019 1 commit
    • Kirill Smelkov's avatar
      gpython: Kill stray `import sys` · c489bd5f
      Kirill Smelkov authored
      sys is imported in the beginning of main, so there is no need to import
      it the second time in the middle of main. The bug was there since
      gpython day1 - since 32a21d5b (gpython: Python interpreter with support
      for lightweight threads).
      c489bd5f
  12. 26 Aug, 2019 4 commits
  13. 14 May, 2019 1 commit
    • Kirill Smelkov's avatar
      *: __future__ += absolute_imports; Use unified __future__ everywhere · 81dfefa0
      Kirill Smelkov authored
      - we are going to introduce golang.time, and from inside there without
        `from __future__ import absolute_imports` it won't be possible to import
        needed stdlib's time.
      
      - we were already doing `from __future__ import print_function`, but
        only in some files.
      
      -> It makes sense to apply updated __future__ usage uniformly.
      81dfefa0
  14. 24 Mar, 2019 1 commit
    • Kirill Smelkov's avatar
      gpython: Workaround PyPy2 vs Gevent patch_thread crash · 704d99f0
      Kirill Smelkov authored
      	pypy-gevent runtests: commands[0] | gpython -m pytest gpython/ golang/
      	Traceback (most recent call last):
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy-gevent/bin/gpython", line 10, in <module>
      	    sys.exit(main())
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy-gevent/site-packages/gpython/__init__.py", line 153, in main
      	    _ = monkey.patch_all()      # XXX sys=True ?
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy-gevent/site-packages/gevent/monkey.py", line 976, in patch_all
      	    patch_thread(Event=Event, _warnings=_warnings)
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy-gevent/site-packages/gevent/monkey.py", line 178, in ignores
      	    return func(*args, **kwargs)
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy-gevent/site-packages/gevent/monkey.py", line 588, in patch_thread
      	    _patch_existing_locks(threading_mod)
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy-gevent/site-packages/gevent/monkey.py", line 492, in _patch_existing_locks
      	    if o._RLock__owner is not None:
      	AttributeError: 'thread.RLock' object has no attribute '_RLock__owner'
      
      It will be fixed on next Gevent release, however until then the crash is there
      and we have to workaround: we can skip patching existing locks as it will be
      the same behaviour of next Gevent release, since its just not possible to patch
      locks created via instantiated C-level classes:
      
      https://github.com/gevent/gevent/commit/d0e04658
      
      We are doing monkey-patching very early, so it should be safe.
      704d99f0
  15. 19 Mar, 2019 1 commit
    • Kirill Smelkov's avatar
      gpython: Don't check for time not being pre-imported on PyPy · e847c550
      Kirill Smelkov authored
      PyPy7 always pre-imports the time module. Without the change tests were
      failing:
      
      	Traceback (most recent call last):
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy3-gevent/bin/gpython", line 10, in <module>
      	    sys.exit(main())
      	  File "/home/kirr/src/tools/go/pygolang/.tox/pypy3-gevent/site-packages/gpython/__init__.py", line 145, in main
      	    '\n\n\t%s\n\nsys.modules:\n\n\t%s' % (bad, sysmodv))
      	RuntimeError: gpython: internal error: the following modules are pre-imported, but must be not:
      
      	        ['time']
      
      	sys.modules:
      
      	        ['__future__', '__main__', '__pypy__', '__pypy__._pypydatetime', '__pypy__.builders', '__pypy__.intop', '__pypy__.os', '__pypy__.thread', '__pypy__.time', '_ast', '_bootlocale', '_codecs', '_collections', '_collections_abc', '_continuation', '_csv', '_frozen_importlib', '_frozen_importlib_external', '_imp', '_io', '_locale', '_multibytecodec', '_operator', '_rawffi', '_rawffi.alt', '_signal', '_sre', '_structseq', '_thread', '_warnings', '_weakref', '_weakrefset', 'abc', 'array', 'builtins', 'codecs', 'copyreg', 'encodings', 'encodings.aliases', 'encodings.ascii', 'encodings.latin_1', 'encodings.utf_8', 'errno', 'gc', 'genericpath', 'gpython', 'marshal', 'os', 'os.path', 'posix', 'posixpath', 'pwd', 're', 'site', 'sre_compile', 'sre_constants', 'sre_parse', 'stat', 'sys', 'time', 'unicodedata']
      e847c550
  16. 13 Mar, 2019 1 commit
    • Kirill Smelkov's avatar
      gpython: Fix pymain to properly setup sys.path[0] · 6b4990f6
      Kirill Smelkov authored
      Pymain was not adding e.g. directory of executed file to sys.path, and
      as the result if there were e.g. 2 files
      
      	dir/hello.py	# imports world
      	dir/world.py
      
      running `gpython dir/hello.py` would fail to import world.
      
      The case for interactive console was also failing to setup sys.argv as
      empty, so it was containing ['/path/to/gpython']. It was also, contrary
      to standard python, unconditionally showing '>>>' prompt even when stdin
      was not a tty.
      
      Fix all that and add a test to cover pymain functionality.
      6b4990f6
  17. 16 Jan, 2019 1 commit