Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sys.executable might be Vim itself with embedded Python (UnpicklingError) #870

Closed
tonitch opened this issue Aug 10, 2018 · 83 comments
Closed
Labels

Comments

@tonitch
Copy link

tonitch commented Aug 10, 2018

(sorry for miss spellings, I'm french and I'll try my best to explain my issue)

Issue

When I try to or when jedi-vim want to help me, a new window of gvim pop-up with main.py oppened from jedi's file instead of the list of propositions and sometimes, when I go back to the previews window, gvim stop working...

Steps to reproduce

here is my _vimrc ::

source $VIMRUNTIME/vimrc_example.vim

let python_highlight_all=1
syntax on

"Enable folding + space to fold
set foldmethod=indent
set foldlevel=99
nnoremap <space> za

set diffexpr=MyDiff()
function MyDiff()
  let opt = '-a --binary '
  if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
  if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
  let arg1 = v:fname_in
  if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
  let arg1 = substitute(arg1, '!', '\!', 'g')
  let arg2 = v:fname_new
  if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
  let arg2 = substitute(arg2, '!', '\!', 'g')
  let arg3 = v:fname_out
  if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
  let arg3 = substitute(arg3, '!', '\!', 'g')
  if $VIMRUNTIME =~ ' '
    if &sh =~ '\<cmd'
      if empty(&shellxquote)
        let l:shxq_sav = ''
        set shellxquote&
      endif
      let cmd = '"' . $VIMRUNTIME . '\diff"'
    else
      let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
    endif
  else
    let cmd = $VIMRUNTIME . '\diff'
  endif
  let cmd = substitute(cmd, '!', '\!', 'g')
  silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3
  if exists('l:shxq_sav')
    let &shellxquote=l:shxq_sav
  endif
endfunction

set nu
set guifont=Courier_new:h11
set encoding=utf-8
set nocompatible
color desert

filetype off
set rtp+=%USERPROFILE%/vim/bundle/Vundle.vim/
call vundle#begin('%USERPROFILE%/vim/bundle/')

Plugin 'vundleVim/Vundle.vim'
Plugin 'scrooloose/nerdtree'
Plugin 'itchyny/lightline.vim'
Plugin 'mattn/emmet-vim'
Plugin 'Xuyuanp/nerdtree-git-plugin'
Plugin 'altercation/vim-colors-solarized'
Plugin 'jiangmiao/auto-pairs'
Plugin 'kien/rainbow_parentheses.vim'
Plugin 'vim-syntastic/syntastic'
Plugin 'nvie/vim-flake8'
Plugin 'tpope/vim-dispatch'
Plugin 'https://github.com/StanAngeloff/php.vim.git'
Plugin 'joonty/vim-phpqa'
Plugin 'davidhalter/jedi-vim'

call vundle#end()
filetype plugin indent on

"if has('gui_running')
"	set background=dark
"	colorscheme solarized
"else
"	colorscheme zenburn
"endif

filetype plugin on
set omnifunc=syntaxcomplete#Complete

Output of “:verbose JediDebugInfo”

when I do this command, the same windows apear with

import sys
import os


def _get_paths():
    # Get the path to jedi.
    _d = os.path.dirname
    _jedi_path = _d(_d(_d(_d(_d(__file__)))))
    _parso_path = sys.argv[1]
    # The paths are the directory that jedi and parso lie in.
    return {'jedi': _jedi_path, 'parso': _parso_path}


# Remove the first entry, because it's simply a directory entry that equals
# this directory.
del sys.path[0]

if sys.version_info > (3, 4):
    from importlib.machinery import PathFinder

    class _ExactImporter(object):
        def __init__(self, path_dct):
            self._path_dct = path_dct

        def find_module(self, fullname, path=None):
            if path is None and fullname in self._path_dct:
                p = self._path_dct[fullname]
                loader = PathFinder.find_module(fullname, path=[p])
                return loader
            return None

    # Try to import jedi/parso.
    sys.meta_path.insert(0, _ExactImporter(_get_paths()))
    from jedi.evaluate.compiled import subprocess  # NOQA
    sys.meta_path.pop(0)
else:
    import imp

    def load(name):
        paths = list(_get_paths().values())
        fp, pathname, description = imp.find_module(name, paths)
        return imp.load_module(name, fp, pathname, description)

    load('parso')
    load('jedi')
    from jedi.evaluate.compiled import subprocess  # NOQA

# Retrieve the pickle protocol.
pickle_protocol = int(sys.argv[2])
# And finally start the client.
subprocess.Listener(pickle_protocol).listen()
@davidhalter
Copy link
Owner

I have no idea what this could be. lol. This sounds like such a weird issue. Anyone else?

@lboulard
Copy link

lboulard commented Aug 16, 2018

+1

Reverting to 0.9.0 from master fixed the issue while editing Python 3 code.
Happen also with function parameters completion.

This is GVim on Windows (all 64bit, GVim and Python) and a new Gvim instance opens on jedi\jedi\evaluate\compiled\subprocess\__main__.py from submodule jedi.

@davidhalter
Copy link
Owner

@micbou Do you have any idea what this could be? I think this might be related to how Jedi starts subprocesses, but I have no idea about these Windows issues. Contrary to YCM Jedi is run directly in VIM's embedded Python.

@lboulard
Copy link

I can no longer reproduce issue editing same python source file after a JediClearCache and a fresh new GVim instance.

@micbou
Copy link

micbou commented Aug 17, 2018

I can reproduce the issue by running the :JediDebugInfo command. This happens because sys.executable inside Vim returns the path to the Vim executable on Windows so, instead of starting a Python environment, Jedi is starting a new instance of Vim on that __main__.py file. A solution would be to overwrite sys.executable with the right path on Windows:

sys.executable = os.path.join(sys.prefix, 'python.exe')

@davidhalter
Copy link
Owner

davidhalter commented Aug 18, 2018

We already do this for prefix anyway, because it gets messed up by virtualenvs, so this would be a good solution I think.

@yexianingyue
Copy link

hello .how did you solve it ? I had the same problem.

@AndreyZhdanov
Copy link

put
py3 import os; sys.executable=os.path.join(sys.prefix, 'python.exe')

into .vimrc or _vimrc file

@davidhalter
Copy link
Owner

@AndreyZhdanov Could you try to put that to the beginning of pythonx/jedi_vim.py? And see if it works?

@AndreyZhdanov
Copy link

@davidhalter Yes. I put
sys.executable=os.path.join(sys.prefix, 'python.exe')

after import os – line 9 and it works fine for me.

But I still prefer to have this piece in _vimrc beer in mind update of the script. And it looks like vim bug not issue with jedi-vim.

What is your opinion ?

@blueyed blueyed added the bug label Oct 14, 2018
@blueyed
Copy link
Collaborator

blueyed commented Oct 14, 2018

  1. Is this broken/weird already with :py import sys; print(sys.executable) and :py3 import sys; print(sys.executable)?

  2. Does it only happen with gvim, or also vim on the terminal/cmd.exe (if you have that)?

  3. how is Python built into Vim? Dynamically? (look for "py" in :version)

Reverting to 0.9.0 from master fixed the issue while editing Python 3 code.

It would be useful to have this git-bisected to the commi where it started to happen.

@blueyed blueyed changed the title new windows (__main__.py) insthead of modification list Windows: opens new GVim windows (__main__.py) Oct 14, 2018
@AndreyZhdanov
Copy link

  1. I don't understand 1st question, the script is loading during startup, command in 1st point could be executed after. When I put these commands in _vimrc everything is fine.
  2. With gvim only.
  3. Dynamically.

@blueyed
Copy link
Collaborator

blueyed commented Oct 24, 2018

@AndreyZhdanov
Re 1.: I've meant to execute the command in a running gvim instance

@tngreene
Copy link

Can confirm: Reverting to 0.9.0 fixed the problem

@blueyed
Copy link
Collaborator

blueyed commented Oct 24, 2018

@tngreene
Can you bisect this to a particular commit?

@tngreene
Copy link

4c430ed536b6484f7c63929a4426d64f981d994e is the first bad commit
commit 4c430ed536b6484f7c63929a4426d64f981d994e
Author: Daniel Hahler <github@thequod.de>
Date:   Sat Jul 28 01:46:12 2018 +0200

    Improve JediDebugInfo for envs (#858)

    Improve JediDebugInfo for envs

    This is taken out of https://github.com/davidhalter/jedi-vim/pull/836.

Fortunately, this does not scream implausible to me.

@blueyed
Copy link
Collaborator

blueyed commented Oct 25, 2018

@tngreene
Does it happen (only) with :JediDebugInfo for you?
I assume 4c430ed triggers it for this case, since it uses jedi.api.environment.

Can you post the output from running the Vim commands from the first point in #870 (comment), please?

@micbou
Copy link

micbou commented Oct 25, 2018

@blueyed Did you miss #870 (comment)? This comment explains the issue and gives a solution so it should only be a matter of implementing it.

@tngreene
Copy link

@tngreene
Does it happen (only) with :JediDebugInfo for you?
I assume 4c430ed triggers it for this case, since it uses jedi.api.environment.

Can you post the output from running the Vim commands from the first point in #870 (comment), please?

Running with :py breaks, because I don't have Python 2 installed. with :py3 it prints C:\Vim\gvim.exe

@blueyed
Copy link
Collaborator

blueyed commented Oct 25, 2018

@micbou
I wanted to understand the issue first.

It is clear now: since Python is linked into GVim gvim.exe appears to be the executable.
Sounds a bit like a GVim bug / build issue though: on Linux it returns a python binary with gvim and vim (dynamically linked also). Please consider reporting it with Vim also.

As for fixing this in jedi/jedi-vim: please submit a PR.

@micbou
Copy link

micbou commented Oct 25, 2018

Sounds a bit like a GVim bug / build issue though: on Linux it returns a python binary with gvim and vim (dynamically linked also). Please consider reporting it with Vim also.

This has already been discussed on the Vim mailing list and it's not an issue with Vim but a peculiarity of Python on Windows: when a program is embedding Python, sys.executable points to the executable of that program instead of the interpreter.

As for fixing this in jedi/jedi-vim: please submit a PR.

I would if I were a user of jedi-vim but I am not.

@tngreene
Copy link

put
py3 import os; sys.executable=os.path.join(sys.prefix, 'python.exe')

into .vimrc or _vimrc file

You missed importing sys

py3 import os; import sys; sys.executable=os.path.join(sys.prefix, 'python.exe')

This made it work for me. Thank you! Looking forward to an official fix, however! That way no one else gets confused.

@lboulard
Copy link

Hi,

Finally, I have again issue of launching gvim.exe instead of python.exe.
I have been able to bisect commit of issue in davidhalter/jedi@f9cbc65 (from pythonx/jedi submodule).

Reverting this commit from version v0.13.1 of jedi allow JediDebugInfo to work correctly.

Hope this help.

@blueyed
Copy link
Collaborator

blueyed commented Oct 29, 2018

@lboulard
Thanks for finding this.

@davidhalter
You said:

We already do this for prefix anyway, because it gets messed up by virtualenvs, so this would be a good solution I think.

Where is that?

I think a fix needs to be applied to https://github.com/davidhalter/jedi/blob/3bdb941daa2d87947fa265ebcf7d94f68efbc42d/jedi/api/environment.py#L133 (if it should be done for Jedi, which makes sense, since Python might be embedded also in non-Vim apps).

@j5shi
Copy link

j5shi commented Nov 20, 2018

Any update about the fix?

@gerroon
Copy link

gerroon commented Nov 25, 2018

I have the same issue.

@davidhalter
Copy link
Owner

davidhalter commented Nov 25, 2018

Where is that?

@blueyed https://github.com/davidhalter/jedi-vim/blob/master/pythonx/jedi_vim.py#L31

I think a fix needs to be applied to https://github.com/davidhalter/jedi/blob/3bdb941daa2d87947fa265ebcf7d94f68efbc42d/jedi/api/environment.py#L133 (if it should be done for Jedi, which makes sense, since Python might be embedded also in non-Vim apps).

I tend to agree. But what would be a good fix? I'm not really sure how to do get the executable path of Python if sys.executable was overridden.

blueyed added a commit to blueyed/deoplete-jedi that referenced this issue Feb 24, 2019
…8a69

    * rplugin/python3/deoplete/vendored/jedi 2f86f54...0bf8a69 (7):
      > v13.3 release notes
      > A small improvement for environments
      > Check for specific Python versions first on unix, see davidhalter/jedi-vim#870
      > Cleanup SameEnvironment and use the same logic for creation in virtualenvs
      > Revert "Remove an used function"
      > Fix embedded Python with Jedi (see comments in source code), fixes davidhalter/jedi-vim#870
      > Remove an used function
@blueyed
Copy link
Collaborator

blueyed commented Feb 24, 2019

@davidhalter
LGTM. But s/parso/jedi in davidhalter/jedi#1063 (comment)

@scrosland
Copy link

@scrosland Thanks for that information! I have used your information in the latest commits to improve the environment selection. Could you please test the latest Jedi commits and see if it still happens?

I updated vim-jedi (and jedi) and it works correctly now without my previous vimrc workaround. Thanks!

clrpackages pushed a commit to clearlinux-pkgs/jedi that referenced this issue Feb 25, 2019
…rce code), fixes davidhalter/jedi-vim#870

Dave Halter (9):
      setup.py was not executable in Python3.7
      Improve an error message, see #1279
      Remove an used function
      Fix embedded Python with Jedi (see comments in source code), fixes davidhalter/jedi-vim#870
      Revert "Remove an used function"
      Cleanup SameEnvironment and use the same logic for creation in virtualenvs
      Check for specific Python versions first on unix, see davidhalter/jedi-vim#870
      A small improvement for environments
      v13.3 release notes

Marc Zimmermann (1):
      fixing permission denied errors with project.json
scrosland added a commit to scrosland/dotfiles that referenced this issue Feb 28, 2019
vim/vimrc: Disable but do not remove the workaround for
davidhalter/jedi-vim#870 now that it is
closed.
netbsd-srcmastr pushed a commit to NetBSD/pkgsrc that referenced this issue May 18, 2020
+++++++++++++++++++

- Added ``Project`` support. This allows a user to specify which folders Jedi
  should work with.
- Added support for Refactoring. The following refactorings have been
  implemented: ``Script.rename``, ``Script.inline``,
  ``Script.extract_variable`` and ``Script.extract_function``.
- Added ``Script.get_syntax_errors`` to display syntax errors in the current
  script.
- Added code search capabilities both for individual files and projects. The
  new functions are ``Project.search``, ``Project.complete_search``,
  ``Script.search`` and ``Script.complete_search``.
- Added ``Script.help`` to make it easier to display a help window to people.
  Now returns pydoc information as well for Python keywords/operators.  This
  means that on the class keyword it will now return the docstring of Python's
  builtin function ``help('class')``.
- The API documentation is now way more readable and complete. Check it out
  under https://jedi.readthedocs.io. A lot of it has been rewritten.
- Removed Python 3.4 support
- Many bugfixes

This is likely going to be the last minor version that supports Python 2 and
Python3.5. Bugfixes will be provided in 0.17.1+. The next minor/major version
will probably be Jedi 1.0.0.

0.16.0 (2020-01-26)
+++++++++++++++++++

- **Added** ``Script.get_context`` to get information where you currently are.
- Completions/type inference of **Pytest fixtures**.
- Tensorflow, Numpy and Pandas completions should now be about **4-10x faster**
  after the first time they are used.
- Dict key completions are working now. e.g. ``d = {1000: 3}; d[10`` will
  expand to ``1000``.
- Completion for "proxies" works now. These are classes that have a
  ``__getattr__(self, name)`` method that does a ``return getattr(x, name)``.
  after loading them initially.
- Goto on a function/attribute in a class now goes to the definition in its
  super class.
- Big **Script API Changes**:
    - The line and column parameters of ``jedi.Script`` are now deprecated
    - ``completions`` deprecated, use ``complete`` instead
    - ``goto_assignments`` deprecated, use ``goto`` instead
    - ``goto_definitions`` deprecated, use ``infer`` instead
    - ``call_signatures`` deprecated, use ``get_signatures`` instead
    - ``usages`` deprecated, use ``get_references`` instead
    - ``jedi.names`` deprecated, use ``jedi.Script(...).get_names()``
- ``BaseName.goto_assignments`` renamed to ``BaseName.goto``
- Add follow_imports to ``Name.goto``. Now its signature matches
  ``Script.goto``.
- **Python 2 support deprecated**. For this release it is best effort. Python 2
  has reached the end of its life and now it's just about a smooth transition.
  Bugs for Python 2 will not be fixed anymore and a third of the tests are
  already skipped.
- Removed ``settings.no_completion_duplicates``. It wasn't tested and nobody
  was probably using it anyway.
- Removed ``settings.use_filesystem_cache`` and
  ``settings.additional_dynamic_modules``, they have no usage anymore. Pretty
  much nobody was probably using them.

0.15.2 (2019-12-20)
+++++++++++++++++++

- Signatures are now detected a lot better
- Add fuzzy completions with ``Script(...).completions(fuzzy=True)``
- Files bigger than one MB (about 20kLOC) get cropped to avoid getting
  stuck completely.
- Many small Bugfixes
- A big refactoring around contexts/values

0.15.1 (2019-08-13)
+++++++++++++++++++

- Small bugfix and removal of a print statement

0.15.0 (2019-08-11)
+++++++++++++++++++

- Added file path completions, there's a **new** ``Completion.type`` now:
  ``path``. Example: ``'/ho`` -> ``'/home/``
- ``*args``/``**kwargs`` resolving. If possible Jedi replaces the parameters
  with the actual alternatives.
- Better support for enums/dataclasses
- When using Interpreter, properties are now executed, since a lot of people
  have complained about this. Discussion in #1299, #1347.

New APIs:

- ``Name.get_signatures() -> List[Signature]``. Signatures are similar to
  ``CallSignature``. ``Name.params`` is therefore deprecated.
- ``Signature.to_string()`` to format signatures.
- ``Signature.params -> List[ParamName]``, ParamName has the
  following additional attributes ``infer_default()``, ``infer_annotation()``,
  ``to_string()``, and ``kind``.
- ``Name.execute() -> List[Name]``, makes it possible to infer
  return values of functions.


0.14.1 (2019-07-13)
+++++++++++++++++++

- CallSignature.index should now be working a lot better
- A couple of smaller bugfixes

0.14.0 (2019-06-20)
+++++++++++++++++++

- Added ``goto_*(prefer_stubs=True)`` as well as ``goto_*(prefer_stubs=True)``
- Stubs are used now for type inference
- Typeshed is used for better type inference
- Reworked Name.full_name, should have more correct return values

0.13.3 (2019-02-24)
+++++++++++++++++++

- Fixed an issue with embedded Python, see davidhalter/jedi-vim#870

0.13.2 (2018-12-15)
+++++++++++++++++++

- Fixed a bug that led to Jedi spawning a lot of subprocesses.

0.13.1 (2018-10-02)
+++++++++++++++++++

- Bugfixes, because tensorflow completions were still slow.

0.13.0 (2018-10-02)
+++++++++++++++++++

- A small release. Some bug fixes.
- Remove Python 3.3 support. Python 3.3 support has been dropped by the Python
  foundation.
- Default environments are now using the same Python version as the Python
  process. In 0.12.x, we used to load the latest Python version on the system.
- Added ``include_builtins`` as a parameter to usages.
- ``goto_assignments`` has a new ``follow_builtin_imports`` parameter that
  changes the previous behavior slightly.

0.12.1 (2018-06-30)
+++++++++++++++++++

- This release forces you to upgrade parso. If you don't, nothing will work
  anymore. Otherwise changes should be limited to bug fixes. Unfortunately Jedi
  still uses a few internals of parso that make it hard to keep compatibility
  over multiple releases. Parso >=0.3.0 is going to be needed.

0.12.0 (2018-04-15)
+++++++++++++++++++

- Virtualenv/Environment support
- F-String Completion/Goto Support
- Cannot crash with segfaults anymore
- Cleaned up import logic
- Understand async/await and autocomplete it (including async generators)
- Better namespace completions
- Passing tests for Windows (including CI for Windows)
- Remove Python 2.6 support
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests