2

有没有办法在每次保存时自动观看 python 脚本文件并在 tmux/screen 中执行它?我主要在 vim 中工作,每次我想评估它在新窗口中打开的代码时,它都会破坏工作流程。我问这个是因为我也在 Scala 中工作,而 sbt 构建工具有非常好的选择来做到这一点(在保存时运行编译器/REPL)

4

2 回答 2

4

如果每次我保存一个 py 文件时,它都会自动执行,那会很烦人。由于您可以编辑 py 文件,因此只需 py 类。或者纯配置的东西。无论如何,如果您希望发生这种情况,您可以尝试:

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

我有的是vimrc

autocmd FileType python call AutoCmd_python()

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

endf

现在你可以手动<F9>下来测试你当前的 python 文件。

于 2013-10-05T23:47:35.317 回答
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
于 2013-10-05T23:55:40.007 回答