Python invoke 不在 Windows 上使用多行命令打印

2024-09-30 02:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

从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中打印输出


Tags: runpytest命令taskwindowsdeftasks
1条回答
网友
1楼 · 发布于 2024-09-30 02:23:12

这是我目前正在使用的黑客方法,以防其他人需要在短期内绕过它。如果遇到问题,我会发回;到目前为止,它只接受了最低限度的测试。基本上,如果您在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

我很高兴听到一个真正的解决方案,不过,如果有人有一个

相关问题 更多 >

    热门问题