質問

Is there a way to automatically watch python script file and execute in it in tmux/screen each time it gets saved? I work mostly in vim and every time i want to evaluate the code it gets opened in new window so it kinda breaks the workflow. I'm asking this because i also work in Scala and sbt build tool has very neat option to do just that (run compiler/REPL on save)

役に立ちましたか?

解決 2

The easy way to do this is, as sean and Kent suggest, to have vim drive it.

However, if you only "mostly" work in vim, that may not be appropriate.

The only other alternative is to write code that uses your platform's filesystem watch APIs, or, if worst comes to worst, periodically polls the file, and runs it on each update. Then just run that code under your screen or tmux (presumably with vim in another screen window).

Since I don't know your platform, I'll write a stupid polling implementation to show the idea—just remember that in real life, you'd be much better off with a tool like inotifywatch/fswatch/etc.:

import os
import subprocess
import sys
import time

scripts = sys.argv[1:]
mtimes = {script: os.stat(script).st_mtime for script in scripts}
while True:
    for script in scripts:
        mtime = os.stat(script).st_mtime
        if mtime != mtimes[script]:
            subprocess.call([script], shell=True)
            mtimes[script] = mtime
    time.sleep(250)

Now, you can do this:

$ screen
$ python watch.py myscript.py
$ ^AS^A<Tab>^A^C
$ vim myscript.py

他のヒント

It would be annoying if every time I save a py file, it gets executed automatically. Since you may edit a py file, just py class. Or pure config stuff. Anyway, if you want that to happen, you can try:

autocmd FileWritePost *.py exec '!python' shellescape(@%, 1)

what I have in my vimrc is:

autocmd FileType python call AutoCmd_python()

fun! AutoCmd_python()
        "setlocal other options for python, then:
    nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr>

endf

now you could just manually press <F9> to test your current python file.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top