VIM - unknown function: pythoncomplete#Complete - python

when I type the following code in a .py - file:
import numpy
numpy.
and then press the TAB key which triggers Omnicompletion, I get the following error:
Error: Required vim compiled with +python
E117: Unknown function: pythoncomplete#Complete
However, when I type vim --version | grep python, I get:
+cryptv +linebreak +python/dyn +viminfo
+cscope +lispindent +python3/dyn +vreplace
Can someone explain this behaviour or does someone have any ideas where to dig? There is a similar question on stackoverflow, but in that case VIM was compiled without python support.

Check again from within Vim with
:echo has('python')
It may be that even though your Vim has been compiled with Python, the dynamic loading of the Python interpreter fails, usually because the corresponding shared library cannot be found. You find its name in the :version output under Compilation:

Apparently, your vim is compiled with dynamic support for both python versions ( python3/dyn and python/dyn ). There is one thing you should keep in mind in this setup:
The command has('python') and has('python3') already invokes the usage of this specific python version exclusively.
So apparently, YCM invokes has('python') before has('python3'), so that python3 becomes active and python2 inactive for the rest of the vim-session. pythoncomplete#Complete somehow only works with python2.
So you could fix pythoncomplete#Complete by explicitly invoking python2 at the very top of your vimrc:
set nocompatible
if has('python') " if dynamic py|py3, this line already activates python2.
let s:python_version = 2
elseif has('python3')
let s:python_version = 3
else
let s:python_version = 0
endif
echomsg 'Using python'.s:python_version
In the rest of your vimrc you can check for python version with s:python_version, if you dont need it, the has commands already to the job.

You might need both python2 & 3 as in my case
let g:python3_host_prog='C:/Bin/Miniconda3/python.exe'
let g:python_host_prog='C:/Bin/miniconda2/python.exe'
:echo has('python') returned 0 until I did this.
Need for YCM & ensime & neoterm in my case
Downloaded directly from the neoterm site (windows obviously for this case)

Related

Is this headline '#!/usr/bin/env python3' still needed from python 3.6 and onwards? [duplicate]

Should I put the shebang in my Python scripts? In what form?
#!/usr/bin/env python
or
#!/usr/local/bin/python
Are these equally portable? Which form is used most?
Note: the tornado project uses the shebang. On the other hand the Django project doesn't.
The shebang line in any script determines the script's ability to be executed like a standalone executable without typing python beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use is important.
Correct usage for (defaults to version 3.latest) Python 3 scripts is:
#!/usr/bin/env python3
Correct usage for (defaults to version 2.latest) Python 2 scripts is:
#!/usr/bin/env python2
The following should not be used (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):
#!/usr/bin/env python
The reason for these recommendations, given in PEP 394, is that python can refer either to python2 or python3 on different systems.
Also, do not use:
#!/usr/local/bin/python
"python may be installed at /usr/bin/python or /bin/python in those
cases, the above #! will fail."
―"#!/usr/bin/env python" vs "#!/usr/local/bin/python"
It's really just a matter of taste. Adding the shebang means people can invoke the script directly if they want (assuming it's marked as executable); omitting it just means python has to be invoked manually.
The end result of running the program isn't affected either way; it's just options of the means.
Should I put the shebang in my Python scripts?
Put a shebang into a Python script to indicate:
this module can be run as a script
whether it can be run only on python2, python3 or is it Python 2/3 compatible
on POSIX, it is necessary if you want to run the script directly without invoking python executable explicitly
Are these equally portable? Which form is used most?
If you write a shebang manually then always use #!/usr/bin/env python unless you have a specific reason not to use it. This form is understood even on Windows (Python launcher).
Note: installed scripts should use a specific python executable e.g., /usr/bin/python or /home/me/.virtualenvs/project/bin/python. It is bad if some tool breaks if you activate a virtualenv in your shell. Luckily, the correct shebang is created automatically in most cases by setuptools or your distribution package tools (on Windows, setuptools can generate wrapper .exe scripts automatically).
In other words, if the script is in a source checkout then you will probably see #!/usr/bin/env python. If it is installed then the shebang is a path to a specific python executable such as #!/usr/local/bin/python (NOTE: you should not write the paths from the latter category manually).
To choose whether you should use python, python2, or python3 in the shebang, see PEP 394 - The "python" Command on Unix-Like Systems:
... python should be used in the shebang line only for scripts that are
source compatible with both Python 2 and 3.
in preparation for an eventual change in the default version of
Python, Python 2 only scripts should either be updated to be source
compatible with Python 3 or else to use python2 in the shebang line.
If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:
#!/usr/bin/python2.7
Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.
#!/usr/bin/env python is generally the better approach, but this helps with special cases.
Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.
The purpose of shebang is for the script to recognize the interpreter type when you want to execute the script from the shell.
Mostly, and not always, you execute scripts by supplying the interpreter externally.
Example usage: python-x.x script.py
This will work even if you don't have a shebang declarator.
Why first one is more "portable" is because, /usr/bin/env contains your PATH declaration which accounts for all the destinations where your system executables reside.
NOTE: Tornado doesn't strictly use shebangs, and Django strictly doesn't. It varies with how you are executing your application's main function.
ALSO: It doesn't vary with Python.
You should add a shebang if the script is intended to be executable. You should also install the script with an installing software that modifies the shebang to something correct so it will work on the target platform. Examples of this is distutils and Distribute.
Sometimes, if the answer is not very clear (I mean you cannot decide if yes or no), then it does not matter too much, and you can ignore the problem until the answer is clear.
The #! only purpose is for launching the script. Django loads the sources on its own and uses them. It never needs to decide what interpreter should be used. This way, the #! actually makes no sense here.
Generally, if it is a module and cannot be used as a script, there is no need for using the #!. On the other hand, a module source often contains if __name__ == '__main__': ... with at least some trivial testing of the functionality. Then the #! makes sense again.
One good reason for using #! is when you use both Python 2 and Python 3 scripts -- they must be interpreted by different versions of Python. This way, you have to remember what python must be used when launching the script manually (without the #! inside). If you have a mixture of such scripts, it is a good idea to use the #! inside, make them executable, and launch them as executables (chmod ...).
When using MS-Windows, the #! had no sense -- until recently. Python 3.3 introduces a Windows Python Launcher (py.exe and pyw.exe) that reads the #! line, detects the installed versions of Python, and uses the correct or explicitly wanted version of Python. As the extension can be associated with a program, you can get similar behaviour in Windows as with execute flag in Unix-based systems.
When I installed Python 3.6.1 on Windows 7 recently, it also installed the Python Launcher for Windows, which is supposed to handle the shebang line. However, I found that the Python Launcher did not do this: the shebang line was ignored and Python 2.7.13 was always used (unless I executed the script using py -3).
To fix this, I had to edit the Windows registry key HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.File\shell\open\command. This still had the value
"C:\Python27\python.exe" "%1" %*
from my earlier Python 2.7 installation. I modified this registry key value to
"C:\Windows\py.exe" "%1" %*
and the Python Launcher shebang line processing worked as described above.
Answer: Only if you plan to make it a command-line executable script.
Here is the procedure:
Start off by verifying the proper shebang string to use:
which python
Take the output from that and add it (with the shebang #!) in the first line.
On my system it responds like so:
$which python
/usr/bin/python
So your shebang will look like:
#!/usr/bin/python
After saving, it will still run as before since python will see that first line as a comment.
python filename.py
To make it a command, copy it to drop the .py extension.
cp filename.py filename
Tell the file system that this will be executable:
chmod +x filename
To test it, use:
./filename
Best practice is to move it somewhere in your $PATH so all you need to type is the filename itself.
sudo cp filename /usr/sbin
That way it will work everywhere (without the ./ before the filename)
If you have different modules installed and need to use a specific
python install, then shebang appears to be limited at first. However,
you can do tricks like the below to allow the shebang to be invoked
first as a shell script and then choose python. This is very flexible
imo:
#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
echo Using preferred python $PREFERRED_PYTHON
exec $PREFERRED_PYTHON "$0" "$#"
elif [ -x $ALTERNATIVE_PYTHON ]; then
echo Using alternative python $ALTERNATIVE_PYTHON
exec $ALTERNATIVE_PYTHON "$0" "$#"
else
echo Using fallback python $FALLBACK_PYTHON
exec python3 "$0" "$#"
fi
exit 127
'''
__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())
Or better yet, perhaps, to facilitate code reuse across multiple python scripts:
#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[#]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$#"; exit 127; '''
and then select.sh has:
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
CHOSEN_PYTHON=$FALLBACK_PYTHON
fi
This is really a question about whether the path to the Python interpreter should be absolute or logical (/usr/bin/env) with respect to portability.
My view after thoroughly testing the behavior is that the logical path in the she-bang is the better of the two options.
Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments is something I really need a solid answer to. Encountering other answers on this and other Stack Overflow sites which talked about the issue in a general way without supporting proofs, I've performed some really granular testing & analysis on this very question on Unix.SE.
For files that are intended to be executable from the command-line, I would recommend
#! /usr/bin/env python3
Otherwise you don't need the shebang (though of course it doesn't harm).
If you use virtual environments like with pyenv it is better to write #!/usr/bin/env python
The pyenv setting will control which version of python and from which file location is started to run your script.
If your code is known to be version specific, it will help others to find why your script does not behave in their environment if you specify the expected version in the shebang.
If you want to make your file executable you must add shebang line to your scripts.
#!/usr/bin/env python3
is better option in the sense that this will not be dependent on specific distro of linux but could be used on almost all linux distro since it hunts for the python3 path from environment variables, which is different for different distros of linux.
whereas
#!/usr/local/bin/python3
would be a distro specific path for python3 and would not work if python3 is not found on this path, and could result in confusion and ambiguity for developer when migrating from one distro to another of linux.
Use first
which python
This will give the output as the location where my python interpreter (binary) is present.
This output could be any such as
/usr/bin/python
or
/bin/python
Now appropriately select the shebang line and use it.
To generalize we can use:
#!/usr/bin/env
or
#!/bin/env

Python 3, vim 8 and the pythoncomplete error

Editing a python file in vim and hitting Ctrl+x followed by Ctrl+o in insert mode results in
Error: Required vim compiled with +python
E117: Unbekannte Funktion: pythoncomplete#Complete
I've read a lot of postings and did a lot of fumbling until this:
I'm using vim 8.0.54
installed python and vim are both 32 bit
Vim :vers returns ... +python/dyn and +python3/dyn
the python35.dll file mentioned in :vers -DDYNAMIC_PYTHON3_DLL=\"python35.dll\" is located in in the same folder as the gvim.exe
in my _vimrc let g:pymode_python = 'python3' should tell vim to user python3
:echo has ('python3') returns 1
But the error still remains... any idea besides the error in front of the keyboard?
update 2016-11-08:
It's not a good way, but it solved my problem. I changed
setlocal omnifunc=pythoncomplete#Complete to
setlocal omnifunc=python3complete#Complete in the python.vim file in the ftplugin-folder. Now it works just fine. Any recommendations to achieve the same without modifying the python.vim file?
update 2016-11-08:
Finally solved it with autocmd BufNewFile *.py :set omnifunc=python3complete#Complete in my _vimrc
Is this a Vim you compiled? The vers results looks correct. The error E117 is specific to calling a function using vim's eval feature.
However, the let g:pymode_python = 'python3 variable is for a specific "python-mode" plugin.
Is the python3 library in your search path?
Were python and python3 compiled with --enable-shared?
are the questions to answer.
Not sure if vim searches it's own executable folder first or not, but to check so, you can do:
To use the Python interface the Python DLL must be in your search path. In a
console window type "path" to see what directories are used.
A bit more insight possible in the docs: doc/if_pyth.html#python-dynamic
HTH

Batch for trying two python versions

The system will have a possible Python version of 2.4.5 or 2.7.9 only. I'm trying to write a batch error handling to try use python 2.7.9 first, and if that fails, use python 2.4.5.
Conditions
System has company installed software and will only have Python 2.4.5 or Python 2.7.9. And I won't know which one, so my scripts have to be backwards compatible.
This is what I have
rem
#echo off
echo Building
"%COMMONPROGRAMFILES%\CompanyName\python\python27\python.exe" build.py
IF ERRORLEVEL 1 GOTO TRY-PYTHON-24
IF ERRORLEVEL 0 GOTO FINISHED-BUILDING
:TRY-PYTHON-24
"%COMMONPROGRAMFILES%\CompanyName\python\python24\python.exe" build.py
IF ERRORLEVEL 0 GOTO FINISHED-BUILDING
:FINISHED-BUILDING:
echo Done
...more code...
Expected Result
Try and use Python 2.7.9 first, if there is ERRORLEVEL 1, then try Python 2.4.5. There won't be an error there. Is this the correct way of writing a batch version of try except statement like Python?
Such as..
try:
...Python 2.7.9...
except:
...Python 2.4.5...
Sources
I wrote this based on Microsoft's guide (https://support.microsoft.com/en-us/kb/39585). But I'm unsure if this is the best method to a try except on two versions of Python.
I can't speak to the general case of try-except constructs in batch files, but there is a much simpler way to solve this particular problem: use the PATH variable. The code shown can be replaced with
#echo off
set "PATH=%PATH%;%COMMONPROGRAMFILES%\WatchGuard\python\python27"
set "PATH=%PATH%;%COMMONPROGRAMFILES%\WatchGuard\python\python24"
python build.py || exit /b
rem ... more code ...
Setting PATH this way makes the batchfile interpreter automatically look for python.exe in both of the directories where it could be. If both versions of Python are installed, it will take the one earlier in the list, i.e. the one in ...\python27. (Note that this means if there is some other version of Python installed in a directory that already appeared in PATH when the script was invoked, that one will be used. This is probably what someone who set their system up that way wants.)
you can use IF EXIST :
set "p279="%COMMONPROGRAMFILES%\WatchGuard\python\python27\python.exe""
set "p245="%COMMONPROGRAMFILES%\WatchGuard\python\python24\python.exe""
if exist %p279% (
set "python=%p279%"
) else (
set "python=%p245%"
)
call %python% build.py

Can Python be run from within the vim editor? [duplicate]

This question already has answers here:
Executing Python with Gvim
(4 answers)
Closed 9 years ago.
Is it possible to run Python code from within the vim editor?
What is necessary to install the support along with Python syntax highlighting?
How would I install "python.vim : Enhanced version of the python syntax highlighting script" ?
I did not automatically create ~/.vim/syntax and I'm using a Mac, all I downloaded was the .app file, an executable that I don't know of its purpose and a readme file.
I've tried also creating a folder for the python.vim file, but that didn't work out either.
Personally:
When inside Vim editing my Python scripts, I simply hit CtrlZ so as to return in console mode.
Run my script with command $ python my_script.py.
When done, I enter $ fg in the command line and that gets me back inside Vim, in the state I was before hitting CtrlZ. (fg as in foreground)
Edit
Recently I have started using the :terminal mode of vim much more frequently.
I tend to prefer it to CtrlZZ because it may happen that I forget that I used Ctrl-z and open an additional vim session: it may become messy. Also, having a terminal pane is easier for dealing with line number in errors message, since the two views are available at the same time.
So the workflow I'm using nowadays has become:
:terminal (in my case I have a vim mapping with leader key) <leader>tm :terminal<cr> so that I don't even type :terminal manually)
Run my script with command $ python my_script.py.
$ exit in the bash command line if I want to close the terminal pane
You don't have to install any plugins to get syntax highlighting for any version of Python in Vim. The python-syntax plugin might have more features, but it's absolutely not needed and not important if you're new to Vim and Python. To enable syntax highlighting add this to your ~/.vimrc:
filetype plugin on
syntax on
Adding to Kent's answer you can also send arguments to the script you're running if you want to.
[args] is something you'd normally add after python script.py.
:w !python - [args]
Personally I prefer to have a seperate shell open in Tmux for running my scripts, and possibly play around with bpython. If I'm not using a Tmux session :sh works fine too, giving you a normal shell. You can get back to vim by doing exit or ctrld.
As for using Python with vim autocomplete is a big part of it, and I can recommend jedi-vim for this. If you want error checking/magic Syntastic is the tool for the job.
This might be a little overwhelming if you're new to both Vim and Python, but I suggest you take it as it comes, step by step. The first step for learning Vim is to do the Vimtutor. Run it by entering vimtutor in a shell.
If you are asking how to run Python code through vim, try this:
EDIT
thank #Zyx for pointing out the problems in my original line, I leave this line here, in order to let reader know where are the problems.
nmap <F9> :!python %<cr>
you could create this au (I saved has("autocmd") part...) in your vimrc:
autocmd FileType python nnoremap <buffer> <F9> :exec '!python' shellescape(#%, 1)<cr>
put this in your .vimrc, then after you editing your .py file, press <f9> vim will try to compile and execute it (via external python interpreter).
how to install that plugin:
https://github.com/hdima/python-syntax#how-to-install

Compatible way to use either :py OR :py3 in vim?

In my .vimrc and my vim plugin UltiSnips I've got a lot of code that looks like that
:py << EOF
print("Hi")
EOF
Now, I want to check if python3 is compiled into Vim via has("python3") and then use :py3 instead of :py. Keeping the python code compatible between python 2 and 3 is not the issue - the issue is to tell vim to use :py3 if is available and :py otherwise.
Has someone a good idea?
You can take advantage on the fact that user defined commands in vim are simply place-in-patter-and-eval statements, and write:
if has("python3")
command! -nargs=1 Py py3 <args>
else
command! -nargs=1 Py py <args>
endif
Then you can use :Py to run python commands the same way as you regularly use :py or :py3.
I have solved this now in an ugly fashion by only checking ONCE for python3 or python, then setting a variable
let g:_uspy=":py " or ":py3 "
and then throwing the << EOF syntax overboard and instead call each line of python via
exec g:_uspy "print('Hello')"
which seems to work okaish. See the full solution in this git blob:
https://github.com/SirVer/ultisnips/blob/da49b4b7c4669bc462a98c9abc71b42d43d408bc/plugin/UltiSnips.vim

Categories

Resources