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

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

Related

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

how to output all the lines into python console in vim?

I have set F2 prompt key with map <f2> :w<cr>:! D:\Python34\python %<cr>,when i open an python file in vim and press F2,the python file will be executed .For a simple example,
here is my python file and opened in gvim .
Now i can't input other python lines ,only thing i can do is to see the result and hit any key to close this window.
What i want is :
when i press F2, (the python file was opened in gvim) ,the python console pop up,and all the files in the python file were copied into the python console automatically,and i can go no to input some lines such as Obj().hello in the python console or go on to edit in gvim ,i am a lazy man ,the gvim and python console all opened waiting to serve me , can i write a vim scripts to achieve the target?
The command :!D:\Python34\python -i % works fine ,i got the ouput
There is still a problem remain,
1)when command :!D:\Python34\python -i % works ,the gvim window will be frozen , i can't drag my mouse to see codes in vim.
2)there is no any python codes in the python console wiondow
So if the program is full of many lines ,and i can't remember the previous content ,worse still, the gvim window frozen ,how can i get the codes?
Avoid blocking
To make the call asynchonous (to avoid that GVIM is blocked during the Python session), use the Windows-specific :!start command:
nnoremap <f2> :w<cr>:!start D:\Python34\python -i %<cr>
List teh codez
I don't know whether it is possible to list the passed source code from the interactive Python debugger. But you can print the file contents before starting it:
nnoremap <f2> :w<cr>:!start cmd /c type % && D:\Python34\python -i %<cr>
Additional tips
You should use :noremap; it makes the mapping immune to remapping and recursion.
As your mapping only works correctly from normal mode, use :nnoremap (or extend it to support visual-mode selections, too).
Maybe Vim plugin Conque will solve your problem:
Installation instrucions are here https://code.google.com/p/conque/
To use just type :ConqueTermVSplit python -i test.py (VSplit is for vertical split - you may use horizontal)
There is no blocking of your window with python code - you may escape interactive mode and switch to your window with Ctrl+W twice
You could approach the problem from the Python angle (2.7).
Keep the file where it is (or save it with some unique name to a temporary directory) and have python load the file directly.
Go to that location in your shell and run python interactively (or have vim spin off an interpreter for you)
Import your file import demo
Experiment with what you have implemented demo.SomeModule().meth()
Make some changes in vim
Reload your python module reload(demo)
Experiment with your code again demo.SomeModule().differentMeth()
You can also have vim create a file with shortcut functions for loading/reloading the file you are working on. When vim kicks off the interpreter, you can have it set this file to the PYTHONSTARTUP environment variable, which is a file the interpreter will automatically load when it starts up. For example, you could have a function called r() to automatically reload the file you are working on.
It's also worth mentioning that reloading modules can be a little weird. If you instantiate some modules then reload the file, only new modules will use the new code; the old modules will run with the old code.

Python script gives `: No such file or directory`

I have several python scripts which work just fine but one script has (as of this morning) started giving me this error if I try to run it from the bash:
: No such file or directory
I am able to run the 'broken' script by doing python script_name.py and after looking around a bit the general idea that I picked up was that maybe my line ending of the hashbang got changed (silently) so I looked at the line ending of a working script and a broken script via the :set list option in VI as indicated in this question -> View line-endings in a text file
Both files appear to end using the same character (a $) so I am kind of at a loss on how to proceed from here. Specifically, how to actually 'see' the line ending in case the set list was not the right method.
PS: The script is executable and the shebang is in there, I stated that it's just this 1 script that was working fine before the weekend but it started giving me this error as of this morning.
-- edit: --
Running the script through dos2unix does get it working again but I would like to know of any way to visualize the line ending somehow in VI(M) or why Geany somehow converted the line endings in the first place (as I never work on a dos/windows system anyhow).
From the comments above it looks like you have dos line endings, and so the hashbang line is not properly processed.
Line ending style are not shown with :set list in Vim because that option is only used when reading/writing the file. In memory line endings are always that, line-endings. The line ending style used for a file is kept in a Vim per-file option, weirdly called fileformat.
To see/change the line ending style from Vim, you can use the following commands:
:set fileformat
:set ff
It will show dos or unix. You want unix, of course ;-).
To change it quickly you can save the file with:
:w ++ff=unix
Or if you prefer:
:set ff=unix
And then save the file normally.
So see all the gory details just do :help fileformat, :help file-formats and :help fileformats
You can also use the dos2unix command to convert the file format
dos2unix
This helped me to run the python scripts
This normally happens when we open files in windows do changes and save it.
if you open the file locate the ^M characters at the end of every line
Thanks
Personally, I find it kinda wrong using direct path to python interpreter. As you dont use windows platform, you should have program env, usually in /usr/bin (/usr/bin/env). Try using following shebang:
#!/usr/bin/env python
Different distros store python binary in /bin or /usr/bin (or some weird locations), and this one makes your script config-independent (as far as possible, here we have possibility that env is stored elsewhere; still - it is less possible that env is not in /usr/bin than that python is mislocated).
I had similiar problem (if not exactly the same) and that worked for me.
Also, I have both python interpreters (2.7.x and 3.x) installed, so I need to use "python3" argument for env. AFAIR usually distros link different names to different binaries, so "env python" will run python2.7 on my system, "env python3" (also python33, or smth like that) will run p3k, and "env python2" (also python27, etc) will run python 2.7.x. Declaring which version of interpreter should be used seems like a good idea too.
I came across this problem editing my code on Windows, checking it in with git, and checking out and running it on Linux.
My solution was: tell git to Do The Right Thing. I issued this command on the Windows box:
git config --global core.autocrlf true
Modified the files and checked them in; voila, no such problem any more.
As discussed on the Git documentation.

How to run Python script with one icon click?

Sorry, for the vague question, don't know actually how to ask this nor the rightful terminologies for it.
How to run a python script/bytecode/.pyc (any compiled python code) without going through the terminal. Basically on Nautilus: "on double click of the python script, it'll run" or "on select then [Enter], it'll run!". That's my goal at least.
When i check the "Allow executing of file as a program" then press [enter] on the file. It gives me this message:
Could not display "/home/ghelo/Music/arrange.pyc".
There is no application installed for Python bytecode files.
Do you want to search for an application to open this file?
Using Ubuntu 12.04, by the way and has to be python 2, one of the packages doesn't work on python 3. If there's a difference between how to do it on the two version, include it, if it's not to much t ask, thank you.
I know it doesn't matter, but it's a script auto renaming & arranging my music files. Guide me accordingly, stupid idiot here. :)
You should make the .py files executable and click on them. The .pyc files cannot be run directly.
Adding " #!/usr/bin/env python " at the top of the .py file works! Hmm, although don't appreciate the pop-up, but nevermind. :P
From PHPUG:
You do not invoke the pyc file. It's the .py file that's invoked. Python is an interpreted language.
A simpler way to make a python exectuable (explained):
1) Add #!/usr/bin/env python at the top of your python executable file (eg. main.py) (it uses the default python - eg. if using arch, that's py3 instead of py2. You can explicitly tell it to run python2/python3 by replacing python with it's version: ex. python2.7)
2) Write the code. If the script is directly invoked, __name__ variable becomes equal to the string '__main__' thus the idiom: if __name__ == '__main__':. You can add all the logic that relates to your script being directly invoked in this if-block. This keeps your executable importable.
3) Make it executable 'chmod +x main.py'
4) Call the script: ./main.py args args
install launcher software in ubuntu 12.04
step 1. paste this command in terminal without quotes
"sudo apt-get install --no-install-recommends gnome-panel"
Step 2. now launch it by ..
gnome-desktop-item-edit --create-new ~/Desktop
Step : in command textbox write
python path_of_your_pyc_file/filename.pyc
eg python /opt/test.pyc
and haha!! you have done.. congrats :)
please check link how to install launcher here
https://askubuntu.com/questions/64222/how-can-i-create-launchers-on-my-desktop

Python IDE on Linux Console

This may sound strange, but I need a better way to build python scripts than opening a file with nano/vi, change something, quit the editor, and type in python script.py, over and over again.
I need to build the script on a webserver without any gui. Any ideas how can I improve my workflow?
put this line in your .vimrc file:
:map <F2> :w\|!python %<CR>
now hitting <F2> will save and run your python script
You should give the screen utility a look. While it's not an IDE it is some kind of window manager on the terminal -- i.e. you can have multiple windows and switch between them, which makes especially tasks like this much easier.
You can execute shell commands from within vim.
Using emacs with python-mode you can execute the script with C-c C-c
you can try ipython. using its edit command, it will bring up your editor (nano/vim/etc), you write your script, and then on exiting you're returned to the ipython prompt and the script is automatically executed.
When working with Vim on the console, I have found that using "tabs" in Vim, instead of having multiple Vim instances suspended in the background, makes handling multiple files in Vim more efficient. It takes a bit of getting used to, but it works really well.
You could run XVNC over ssh, which is actually passably responsive for doing this sort of thing and gets you a windowing GUI. I've done this quite effectively over really asthmatic Jetstart DSL services in New Zealand (128K up/ 128K down =8^P) and it's certainly responsive enough for gvim and xterm windows. Another option would be screen, which lets you have multiple textual sessions open and switch between them.
There are actually 2 questions. First is polling for a console IDE for python and the second is a better dev/test/deploy workflow.
For while there are many ways you can write python code in the console, I find a combination of screen, vim and python/ipython is the best as they are usually available on most servers. If you are doing long sessions, I find emacs + python-mode typically involves less typing.
For a better workflow, I would suggest setting up a development environment. You can easily setup a Linux VM on your desktop/laptop easily these days - there isn't a excuse not to even if it's for hobby projects. That opens up a much larger selection of IDEs available to you, such as:
GUI versions of VI and friends
Remote file editing with tramp and testing locally with python-mode inside Emacs
http://www.netbeans.org
and of course http://eclipse.org with the PyDev plugin
I would also setup a SCM to keep track of changes so that you do
better QA and use it to deploy tested changes onto the server.
For example I use Mercurial for my pet projects and I simply tag my repo when it's ready and update the production server to the tag when I deploy. On the devbox, I do:
(hack hack hack, test test test)
hg ci -m 'comment'
hg tag
hg push
Then I jump onto the server and do the following when I deploy:
hg update
restart service/webserver as needed
Well, apart from using one of the more capable console editors (Emacs or vi would come to mind), why do you have to edit it on the web server itself? Just edit it remotely if constant FTP/WebDAV transfer would seem to cumbersome.
Emacs has Tramp Mode, gedit on Linux and bbedit on the Mac support remote editing, too. Probably quite a large number of other editors. In that case you would just edit in on a more capable desktop and restart the script from a shell window.
For what it's worth, VIM alone can do the same tasks as previously posted. I have had the same problem with testing Python from the command line.
My solution was to use the screen command. I split screens vertically, I run Python in one instance of a shell, and on the second screen, I usually edit Python code with VIM.
Command to install screen:
sudo apt-get install screen
The screen package has a bit of a learning curve but there isn't any mystery if you can remember the "Ctrl-Alt ?" command that contains all knowledge.
No GUI is required!

Categories

Resources