如何观看 python 个源代码文件并在保存时重新启动?

How do i watch python source code files and restart when i save?

当我保存一个 python 源代码文件时,我想重新 运行 脚本。是否有像这样工作的命令(有点像节点的 nodemon)?

虽然在 python 生态系统中可能有一些方法可以做到这一点,例如 watchdog/watchmedo(https://github.com/gorakhargosh/watchdog ), and maybe even linux scripting options with inotifywait ( https://linux.die.net/man/1/inotifywait ), for me, the easiest solution by far was... to just use nodemon! What I didn't know is that although the github tagline of nodemon is "Monitor for any changes in your node.js application and automatically restart the server - perfect for development" actually nodemon is a delicously generic tool and knows that .py files should be executed with python for example. Here's where I think the magic happens: https://github.com/remy/nodemon/blob/c1211876113732cbff78eb1ae10483eaaf77e5cf/lib/config/defaults.js

最终结果是下面的命令行完全有效。耶!

$ nodemon hello.py
[nodemon] starting `python hello.py`

您可以安装 nodemon 来监视文件更改。

例如

npm i -g nodemon

然后使用:

nodemon --exec python3 hello.py 

这适用于在命令行中使用 python3 的情况。在 windows 上,您也可以改用 'py'。

我发现与 nodemon 最相似的方法是使用 watchdog 包:

pip install watchdog

这带有一个名为 watchmedo 的实用程序:

watchmedo shell-command \
 --patterns="*.py" \
 --command='python "${watch_src_path}"' \
 .

现在只需在您的 .py 上工作,它会在您每次保存文件时执行。

您实际上可以将 nodemon 与 python 一起使用,来自他们的文档:

Running non-node scripts nodemon can also be used to execute and monitor other programs. nodemon will read the file extension of the script being run and monitor that extension instead of .js if there's no nodemon.json:

nodemon --exec "python -v" ./app.py

Now nodemon will run app.py with python in verbose mode (note that if you're not passing args to the exec program, you don't need the quotes), and look for new or modified files with the .py extension.

https://github.com/remy/nodemon#running-non-node-scripts

我只用npx nodemon pythonfile.py 它 works.Make 确定您使用的是 nodemon v2。0.x 或以上