2

I have a simple python script:

$ cat ~/simple.py
import os
import sys


def write_greeting(inpath):
    outpath = os.path.splitext(inpath)[0] + '.txt'
    with open(outpath, 'w') as f:
        f.write('hello world!')
    sys.stdout.write('wrote {}!'.format(outpath))
    return None


if __name__ == '__main__':
    write_greeting(sys.argv[1])

For example, running

$ python ~/simple.py ~/path/to/foo.bar

creates a text file ~/path/to/foo.txt reading hello world!. After ~/path/to/foo.txt is created, the message wrote ~/path/to/foo.txt! is printed to stdout.

Now, say I'm editing a file ~/path/to/foo.bar in emacs. I want to run simple.py on the file I'm currently editing from within emacs. After my script is called, I want to insert the contents from stdout where my cursor is.

Is this possible?

Essentially, I'd like to automate the sequence of commands:

C-u M-! python ~/simple.py ~/path/to/current/file/name

with a function M-x my-python-script.

Drew
  • 75,699
  • 9
  • 109
  • 225
Brian Fitzpatrick
  • 2,265
  • 1
  • 17
  • 40
  • Take a look at [`call-process`](https://www.gnu.org/software/emacs/manual/html_node/elisp/Synchronous-Processes.html). Here's an [example usage](https://github.com/xiongtx/jdecomp/blob/master/jdecomp.el#L140-L145). – Tianxiang Xiong Aug 01 '17 at 01:13

1 Answers1

3

Absolutely possible:

(defun my-run-python-script-whatever ()
  (interactive)
  (insert (shell-command-to-string (format "python3 %s" buffer-file-name))))
kuanyui
  • 1,020
  • 6
  • 16