Using python2.7 with Emacs 24.3 and python-mode.el - python

I'm new to Emacs and I'm trying to set up my python environment. So far I've learned that using "python-mode.el" in a python buffer C-c C-c loads the contents of the current buffer into an interactive python shell, apparently using what which python yields. In my case that is python 3.3.3. But since I need to get a python 2.7 shell, I'm trying to get Emacs to spawn such a shell on C-c C-c. Unfortunatly I can't figure out, how to do this. Setting py-shell-name to what which python2.7 yields (i.e. /usr/bin/python2.7) does not work. How can get Emacs to do this, or how can I trace back what Emacs executes when I hit C-c C-c?

python-mode.el, execute a python buffer using python2:
M-x py-execute-buffer-python2
or put this in .emacs file:
(custom-set-variables
'(py-force-py-shell-name-p t)
'(py-shell-name "python2"))
python-mode.el checks py-force-py-shell-name-p variable when executing py-execute-buffer(bound to C-c C-c key), and if this variable is set to true("t"), then use python interpreter name saved in py-shell-name.
Alternatively, this customization can be done in M-x customize, Programming>Languages>Python Mode, search there for "Py Force Py Shell" and "Py Shell Name" lines.
It will add this customization code to your .emacs file.
Emacs help(describe function):
C-h f py-execute-buffer TAB
You can send selected region in a python buffer to any interpreter:
C-u 3 M-x py-execute-region
Emacs will prompt every time for a python interpreter name you want to use.
The prefix numerical argument may be any number except 1 or 4, otherwise it will use a default interpreter without prompt.
To execute a buffer in different python interpreters you can select whole buffer by C-x h and then use this prefixed command.

I don't use python, but from the source to python-mode, I think you should look into customizing the variable python-python-command - It seems to default to the first path command matching "python"; perhaps you can supply it with a custom path?

Related

M-x run-python to get a Ipython shell in emacs [duplicate]

I'm trying to run Python code for testing and debugging using Emacs. How should I debug and run code in *.py files ? I tried using the M-x compile commands . Using M-x compile, I get a compilation buffer that crashes (It says Python is compiling, but then nothing happens).
If you are using emacs24 this should be the default (in emacs23 you need python.el, not python-mode.el):
In a python buffer:
C-c C-z : open a python shell
C-c C-c : run the content of the buffer in the opened python shell
C-c C-r : run the selected region in the python shell
default python shell is "python", if you need to use ipython you can use this conf in your .emacs
(setq
python-shell-interpreter "ipython"
python-shell-interpreter-args "--colors=Linux --profile=default"
python-shell-prompt-regexp "In \\[[0-9]+\\]: "
python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
python-shell-completion-setup-code
"from IPython.core.completerlib import module_completion"
python-shell-completion-module-string-code
"';'.join(module_completion('''%s'''))\n"
python-shell-completion-string-code
"';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
provided that you have ipython installed in your system of course :)
ipython>=5 has a auto-complete feature which breaks the emacs sub-shell, you can fix this by changing this line
python-shell-interpreter-args "--colors=Linux --profile=default"
and add --simple-prompt.
It will allow you to see ipython correctly but for some reason I did not get yet the auto-completion in emacs is not as effective as it used to be.
How do you run Python code using Emacs?
I'm running Emacs 26, vanilla dev version (self compiled from source cloned from Savannah).
(Note that in emacs docs, we usually see, for example, Ctrl-c denoted as C-c)
In Python mode (which I usually enter by using C-x C-f to "find" a (possibly new) file ending in .py), you can start a Python shell with and then execute your buffer's
if __name__ == '__main__': with:
C-c C-p (which executes run-python to create a shell with Inferior Python major mode, Shell-Compile minor mode)
C-u C-c C-c (which executes python-shell-send-buffer with a prefix argument)
We require the prefix argument to send the if __name__ == '__main__': block to the inferior Python shell.
We can see all of the Ctrl-c commands with Ctrl-c ?
C-c C-c python-shell-send-buffer
C-c C-d python-describe-at-point
C-c C-f python-eldoc-at-point
C-c C-j imenu
C-c C-l python-shell-send-file
C-c C-p run-python
C-c C-r python-shell-send-region
C-c C-s python-shell-send-string
C-c C-t Prefix Command
C-c C-v python-check
C-c C-z python-shell-switch-to-shell
C-c < python-indent-shift-left
C-c > python-indent-shift-right
C-c C-t c python-skeleton-class
C-c C-t d python-skeleton-def
C-c C-t f python-skeleton-for
C-c C-t i python-skeleton-if
C-c C-t m python-skeleton-import
C-c C-t t python-skeleton-try
C-c C-t w python-skeleton-while
Inspecting the help for python-shell-send-buffer (by clicking it), we see:
python-shell-send-buffer is an interactive compiled Lisp function in
‘python.el’.
(python-shell-send-buffer &optional SEND-MAIN MSG)
Send the entire buffer to inferior Python process.
When optional argument SEND-MAIN is non-nil, allow execution of
code inside blocks delimited by "if __name__== '__main__':".
When called interactively SEND-MAIN defaults to nil, unless it’s
called with prefix argument. When optional argument MSG is
non-nil, forces display of a user-friendly message if there’s no
process running; defaults to t when called interactively.
According to the docs C-u is a prefix argument - and seems to be the most generic one.
A workaround that lets us avoid using the prefix argument C-u is using parentheses:
if (__name__ == '__main__'):
main()
instead of the usual:
if __name__ == '__main__':
main()
and then C-c C-c by itself executes the main function.
In my opinion, M-! and M-& are underrated. Often you just want to start the current script you are working on, no need to complicate things.
Of course, you can use M-x compile, as long as you don't have to provide interactive input. If you do have to provide interactive input, M-x shell is your friend.
If you want to run stuff with one button press, check out F3 and F4 to record a keyboard macro and replay it (the macro can also be bound to a key, e.g. F5).
In each of these cases, there is no "magic" taking place. Emacs does not know how to "compile" or "run" python scripts. You have to provide/overwrite a sensible command line invocation, like:
Compile Command: ipython <yourscriptname>.py
The python subshell is cool where a REPL development style makes sense, but at least on Windows matplotlib, tkinter and other libraries that have to deal with the Windows Message Loop tend to block/hang upon displaying GUI elements.
Once you open your python file in Emacs, you will need to start the python process with:
M-x run-python or C-c C-p, which creates an inferior python shell buffer. This buffer will be created by a horizontal split, and the active buffer will be the one containing the python file.
Then you can do C-c C-c, which will send the current python buffer to the inferior python shell below. This is where you will see the output of your python file.
To switch to and from your python file buffer and the inferior python shell buffer, you can do C-x o.
If you accidentally close one of the buffers, you can switch between buffers with C-x C-<left_arrow> and C-x C-<right_arrow> and perform operations on the python buffer like the ones mentioned by Aaron Hall.
NOTE:
Running GNU Emacs 26.2 without any extensions.
Did not define if (__name__ == '__main__'): block

Open second python interpreter in emacs

How would I open a second python interpreter in emacs? I am using emacs 24.3 and Ubuntu 12.04 LTS. I have opened the SQL interpreter/program via a prefix argument of 2. I tried this with python and it did not work.
Any suggestions and ideas are welcome. The mode in my current python interpreter buffer says: Inferior Python: run Shell-Compile I have downloaded python-mode 6.10 from ELPA the emacs package manager.
Thanks for all the help!
M-x describe-function (RET) run-python:
run-python is an interactive compiled Lisp function in `python.el'.
(run-python &optional CMD NOSHOW NEW)
Run an inferior Python process, input and output via buffer Python.
CMD is the Python command to run. NOSHOW non-nil means don't show the
buffer automatically.
Interactively, a prefix arg means to prompt for the initial Python
command line (default is `python-command').
A new process is started if one isn't running attached to
python-buffer', or if called from Lisp with non-nil arg NEW.
Otherwise, if a process is already running inpython-buffer', switch
to that buffer.
...
In the *scratch* buffer:
(run-python nil nil 't)
That will give you a new Inferior Python process.
You could code up a new interactive emacs command in your .emacs file, something like:
(defun my-run-python ()
(interactive)
(run-python nil nil 't))
C-u M-x python
BTW your python-mode version is outdated.
Recommend to fetch a new one doing
bzr branch lp:python-mode
or visit
https://launchpad.net/python-mode

python 3 in emacs

I changed two days ago to Emacs 23, which lately gave me a lot of headache, especially, as I have two Python versions installed, the older 2.7 and 3. As I generally want to start the python 3 interpreter, it would be nice if I could tell Emacs in some way to use python 3 instead of 2.7.
Besides, I could not find a module which helps to highlight python3 syntax. I am currently using python-mode.el for highlighting.
Also, if somebody had a good tip for which module would be best to show the pydoc, I would be very thankful.
Thanks in advance!
If you're using python-mode.el, you can specify the binary to be executed as an inferior process by setting the py-python-command variable, i.e.:
(setq py-python-command "python3")
Naturally, you'll need to provide the name of the binary as it exists on your system in place of "python3", if it differs. In python.el, the analogous variable to set is python-python-command.
As far as using pydoc, there are a few possibilities. First, you can simply execute help() inside the Python inferior process. If you do choose that option, you might find it useful to add the following code to your .emacs file:
(setenv "PAGER" "cat")
This is necessary because interactive pagers (e.g., less, more, most, etc.) don't work particularly well inside inferior process buffers. Second, you can install a Texinfo package containing the documentation and use Emacs's info browser (q.v., Python Programming in Emacs). Finally, if you opt to use python.el, it includes an interactive function called python-describe-symbol that can lookup pydoc help on demand (and I suspect python-mode.el should have something similar). If you search around a bit, I'm sure you can find other methods and/or third-party packages as well.
[RET] = enter or return key.
M = Meta or Alt key.
If you feel like letting Emacs do the heavy lifting for you, go through the Emacs settings dialogue to have Emacs set it automatically.
M-x customize-variable [RET] python-shell-interpreter [RET]
A new buffer should appear where you can customize the python interpreter you are using.
The field to the right of Python Shell Interpreter: will be the current interpreter your are using. In my case it was python so I changed it to python3. Then move the curer to select the Apply and Save button above and hit [RET] to make Emacs respect the new setting. Alternatively you can click the button with the mouse.
Next time you open the Emacs python interpreter, it will be using the new python you set from the setting dialogue.
After I did the following thing, I got the behavior that: when editing a Python file in emacs, C-c C-p creates a new buffer with a Python3 interpreter.
Add to your .emacs file the following:
(defcustom python-shell-interpreter "python3"
"Default Python interpreter for shell."
:type 'string
:group 'python)
The reason I tried this, was because I found
(defcustom python-shell-interpreter "python"
"Default Python interpreter for shell."
:type 'string
:group 'python)
in python.el. And I hypothesized (i) that the "python" could be substituted with "python3" and (ii) that this would override the definition in python.el.
It is likely that there are reasons why this is inelegant or heavy-handed or otherwise bad. I am an emacs newb.
start an python-interpreter
M-x python RET
(the default interpreter)
M-x pythonVERSION
where VERSION means any installed version
Inspired by #serv-inc's answer you can also put
(setq python-shell-interpreter "python3")
into your ./.emacs.d/init.el or where you store your configuration.
It's December 2020, I'm using EMACS 25, otherwise unconfigured for python, and I found that:
(setq python-shell-interpreter "python3")
added to my .emacs file did the business and led to a reasonably intuitive way of working with python3. C-c C-c sends my file to the interpreter (or asks me to start a new interpreter, and tells me how).
Of course, now the python3 interpreter runs for any python file, so python 2 programs don't work.
I am imagining a better world where emacs looks at the #!/usr/bin/env python2 line at the top of my file and figures out which interpreter to start by some kind of insane high-tech magic.
Note python-mode.el knows a hierarchy how to detect the version needed
a shebang precedes setting of py-shell-name
while py-execute-THING-PYTHONVERSION
would precede also shebang for the command being
see menu PyExec

Python mode in Emacs: No such file or directory, pdb

I have a python script that I want to debug with python-mode. I read in this thread that I can debug my python script with M-x pdb, however I get the following error:
Searching for program: no such file or directory, pdb
I can provide python -m pdb my_source_file.py in the prompt in the minibuffer, but it would be nice if Emacs could infer this command directly from the file on which I run M-x pdb
Update:
Running on:
Red Hat Enterprise Linux Server release 5.1 (Tikanga)
Emacs 23.3.1
Differences between paths
I get different paths when I run M-: exec-path and when I run M-: (getenv "PATH") (the one returned by M-: (getenv "PATH") is longer).
With this:
Where is pdb located? How can I add it to the Emacs path?
Is there a way to ask Emacs to also look into the paths held by the environment variable PATH?
Further to my comment earlier, and your subsequent update to the question:
First figure out a value for $PATH that works in your terminal. Use which pdb to find where the pdb executable is located.
Then, set the $PATH environment variable explicitly in Emacs, and sync it to exec-path as follows:
(setenv "PATH" "/usr/local/bin:/usr/bin:/bin:/some/other/dir")
(setq exec-path (split-string (getenv "PATH") path-separator))
It's possible you would need to also explicitly set PYTHONPATH or similar environment variables; you can do that using lines like the "setenv" line above, or just use the exec-path-from-shell elisp package.
Update
Okay, so it turns out Emacs' pdb command isn't provided by python-mode, and it expects to find an executable called "pdb". The easy way to fix this, then is to create a shell wrapper called "pdb", in a directory on your $PATH:
#!/bin/sh
exec python -m pdb "$#"
(I found a note here suggesting this technique.)
The equivalent under Windows would be a file called pdb.bat, containing:
python -u -m pdb %1
(The -u prevents Python from buffering its output.)
To run the Python Debugger, M-x pdb expects to find an executable named pdb. While the pdb executable may exist in some Python distributions, it doesn't exist in all of them.
A proposal to fix this is in GNU bug report #21521: pdb default suggested command.
Until the bug is fixed, you can set the variable gud-pdb-command-name to define the command used to launch pdb. In .emacs, add...
(setq gud-pdb-command-name "python -m pdb")
At a shell prompt type
which pdb
In Emacs, type M-x customize. Select Programming > Tools > Gud. Set the value of gud-pdb-command-name to the path returned by which pdb.
If your version of Emacs presents a different organization for the customize menu, you could also try
C-h v gud-pdb-command-name
Then click on the customize link, and set the path to pdb there.
Though the instructions above are different, I found this out by reading "Running pdb under emacs" .
You can create a custom command like this:
;; PDB command line
(defun user-python-debug-buffer ()
"Run python debugger on current buffer."
(interactive)
(setq command (format "python -u -m pdb %s " (file-name-nondirectory buffer-file-name)))
(let ((command-with-args (read-string "Debug command: " command nil nil nil)))
(pdb command-with-args)))
In Emacs 23.3.1 and presumably higher, yet another variation is to use the Emacs shell, Eshell (M-x eshell). Under Eshell, there's a pre-existing, Lisp-based definition of pdb. These Lisp functions work in Eshell just like ordinary shell commands.
So pdb "./manage.py runserver" will start a Django server, for instance.
Everyone is going wild saying you gotta make a pdb file and make it an executable and then type ./pdb your_code.py. It is easier than that.
Be where you want to run the debugger from. Probably in your python file, maybe use M-x cd to get somewhere.
Then type: M-x pdb
It will prompt you with:
Run pdb (like this):
You want to make that look like:
Run pdb (like this): python -m pdb your_code.py
Sometimes if I want to run my code as a module.
Run pdb (like this): python -m pdb -m some_package.my_code
Then type help and go read this https://docs.python.org/3/library/pdb.html
My answer builds on what #Chad Nouis mentioned.
a link
However, I've added this to python-mode, everytime python-mode loads, it will set gud-pdb-command-name to "python -m pdb"
;; Set the PDB command
(add-hook 'python-mode-hook
(lambda () (setq gud-pdb-command-name "python -m pdb")))

Debugging python programs in emacs

How do I debug python programs in emacs? I'm using python-mode.el
I've found references suggesting:
import pdb; pdb.set_trace();
but I'm not sure how to use it.
Type M-x cd to change directory to the location of the program you wish to debug.
Type M-x pdb. You'll be prompted with Run pdb (like this): pdb. Enter the name of the program (e.g. test.py).
At the (Pdb) prompt, type help to learn about how to use pdb.
Alternatively, you can put
import pdb
pdb.set_trace()
right inside your program (e.g. test.py). Now type M-x shell to get a shell prompt. When you run your program, you'll be dumped into pdb at the point where pdb.set_trace() is executed.
For me, I needed to replace the default "pdb" with
python -m pdb myscript.py
The realgud package (available from MELPA) supports PDB (among a gazillion other debuggers), and has a host of neat features that Emac's PDB doesn't have.
The one I like best is the shortkeys mode. Once you start debugging a program, you can press n, s, c etc. right in the source window, instead of having to type these commands in the PDB buffer. It also supports Visual-Studio style keybindings with function keys (f10, f11, f5, etc).
After installing RealGUD, you need to run M-x load-feature realgud to load it, and you can start pdb with M-x realgud:pdb.

Categories

Resources