Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: pass arguments to inferior Python shell during buffer evaluation

Tags:

python

emacs

ide

recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buffer is evaluated with C-c C-c. Thanks for help.

like image 671
Sammy Avatar asked May 25 '10 14:05

Sammy


1 Answers

This doesn't appear to be easily possible; the inferior process managed by the python.el module is designed to persist across many invocations of python-send-buffer (and friends). One solution I've found is to write your own function that sets sys.argv programmatically from within the inferior process:

(defun python-send-buffer-with-my-args (args)
  (interactive "sPython arguments: ")
  (let ((source-buffer (current-buffer)))
    (with-temp-buffer
      (insert "import sys; sys.argv = '''" args "'''.split()\n")
      (insert-buffer-substring source-buffer)
      (python-send-buffer))))

Execute this function in your *scratch* buffer and/or save it in your .emacs file, then, if you want, bind it to a convenient key sequence. C-c C-a doesn't seem to be used by python-mode, so perhaps:

(global-set-key "\C-c\C-a" 'python-send-buffer-with-my-args)

The command will prompt you for arguments to use, then copy your source buffer into a temporary buffer, prepending it with a code snippet that sets sys.argv to the list of arguments you supplied, and finally will call python-send-buffer.

The above code will just naively split the string you type on whitespace, so if you need to supply arguments that have whitespace in them, you'll need a more sophisticated algorithm.

like image 123
Sean Avatar answered Jan 09 '23 04:01

Sean