在Windows中使用invoke库时,如果命令跨越多行,似乎没有输出输出到终端。下面是一个重现的示例;将其放入tasks.py
中。
import invoke
@invoke.task
def test_oneline(ctx):
ctx.run("pip install nonexistant-package1234")
@invoke.task
def test_multiline(ctx):
ctx.run(
"""
pip install nonexistant-package1234
"""
)
然后,从tasks.py
所在目录的命令提示符中,我得到了以下内容:
>invoke test-oneline
Collecting nonexistant-package1234
Could not find a version that satisfies the requirement nonexistant-package1234 (from versions: )
No matching distribution found for nonexistant-package1234
>
>invoke test-multiline
>
在Linux上做同样的事情(好吧,至少是Linux的Windows子系统)可以按预期工作:
$ invoke test-multiline
Collecting nonexistant-package1234
Could not find a version that satisfies the requirement nonexistant-package1234 (from versions: )
No matching distribution found for nonexistant-package1234
$
有没有办法在Windows中打印多行命令的输出?
发布于 2019-02-22 03:36:28
这是我现在使用的技巧,以防其他人在短期内需要绕过这一点。如果我遇到问题,我会回复的;到目前为止,它只经过了最低限度的测试。基本上,如果你在Windows上,我只是把命令写到一个.bat
文件中,然后我运行.bat
文件(作为一个单行命令)。
import invoke
import platform
from pathlib import Path
from tempfile import TemporaryDirectory
def _fixed_run(ctx, cmd: str, *args, **kwargs):
if platform.system() != "Windows":
return ctx._old_run(cmd, *args, **kwargs)
with TemporaryDirectory() as tmp_dir:
tmp_file = Path(tmp_dir) / "tmp.bat"
tmp_file.write_text("@echo off\r\n" + cmd)
return ctx._old_run(str(tmp_file), *args, **kwargs)
invoke.Context._old_run = invoke.Context.run
invoke.Context.run = _fixed_run
为了方便使用,请将其保存到一个文件中(例如,fix_invoke.py
,然后在需要此修复程序时执行import fix_invoke
)。
不过,我很高兴听到一个真正的解决方案,如果有人有的话!
https://stackoverflow.com/questions/54813582
复制相似问题