【问题标题】:How can I redirect standard output to a program in CMD?如何将标准输出重定向到 CMD 中的程序?
【发布时间】:2021-01-21 15:49:46
【问题描述】:

我在命令提示符下运行这个:

python -c ""print("""Message from python""")"" | AcceptMessage.exe

但是,这不起作用。我收到消息:

close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

AcceptMessage.exe 接受一个参数。它所做的只是打印出传递给它的内容。这意味着,如果您通常通过AcceptArgument.exe argument_here 调用它,则输出将为argument_here。我已经测试了实际的程序,它可以正常工作,所以这不是问题。

总的来说,我对脚本编写很陌生,所以我很感激任何帮助。

【问题讨论】:

  • 看起来像接受 exe 不读取输入流。您必须使用 for /f 捕获 python 输出并将其作为参数传递以接受 exe
  • 类似for /f %q in (python -c ""print("""Message""")"") do AcceptMessage.exe %q?我刚收到"") was unexpected at this time.

标签: windows batch-file scripting command-prompt


【解决方案1】:

尝试这样(使用 .bat 扩展名保存脚本)

0<0# : ^
''' 
@echo off

for /f "tokens=* delims="  %%a in ('python "%~f0" %*') do (
    AcceptMessage "%%a"
)
exit /b 0
'''

print("message from python")

或类似:

@echo off

for /f "tokens=* delims=" %%a in ('"python -c ""print("""Message from python""")"""') do (
    acceptMessage "%%a"
)

如果你想直接从命令行运行它:

for /f "tokens=* delims=" %a in ('"python -c ""print("""Message from python""")"""') do @AcceptMessage "%a"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2020-10-01
    • 2012-08-15
    相关资源
    最近更新 更多