在 Python 3.12 中处理 Inkscape 交互式 shell

问题描述 投票:0回答:1

我想在 shell 模式下使用 inkscape,因为它更快。我想启动一次 shell,然后一一发出命令并捕获来自 stdout 的响应,最后关闭交互式 shell(使用 quit)。我找到并改编了据说可以执行此操作的代码,并提供了一个输入窗口来发出命令。不幸的是,这根本不起作用,并且在输入不退出的命令后,程序会无限期挂起。如何接收每个命令的打印到控制台?我希望程序等到命令生成所有输出后再打破 send_command 中的循环。

import subprocess

# Path to the Inkscape executable
INKSCAPE_EXE_PATH = r"C:\Program Files\Inkscape\bin\inkscape.exe"

# Start the Inkscape shell and redirect stdout and stderr to pipes
proc = subprocess.Popen(
    [INKSCAPE_EXE_PATH, "--shell"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
    encoding='latin-1',
    bufsize=1,  # Line-buffered for reading output line by line
)

# Define a function to send a command to the subprocess and get its output
def send_command(command):
    proc.stdin.write(command + '\n')
    proc.stdin.flush()
    output = ''
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        output += line
    return output

# Interact with the subprocess
while True:
    user_input = input("Enter a command (or 'exit' to quit): ")
    if user_input == 'exit':
        break

    result = send_command(user_input)
    print(result)

# Close the subprocess and wait for it to finish
proc.stdin.close()
proc.wait()

print("Subprocess exited with return code:", proc.returncode)
python inkscape interactive-shell
1个回答
0
投票
def send_command(command):
    proc.stdin.write(command + '\n')
    proc.stdin.flush()
    output = ''
    while True:
        line = proc.stdout.readline()
        if not line:
            break
        output += line
    return output

您正确地依赖于

readline()
返回包含终止换行符的行,以便
output
保留所述行。这也意味着
not line
永远不会为 true(因为
not "\n"
为 false),并且循环永远不会退出。

if not line.rstrip():
    break

调试器(或在悬挂的部分打印调试)会揭示这一点。

© www.soinside.com 2019 - 2024. All rights reserved.