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.

1

1 Answer 1

3

Absolutely possible:

(defun my-run-python-script-whatever ()
  (interactive)
  (insert (shell-command-to-string (format "python3 %s" buffer-file-name))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.