Gio.Subprocess 中的多个参数

Multiple arguments in Gio.Subprocess

我目前正在开发我的第一个 gnome-shell-扩展。在扩展中,我想执行一个简单的 shell 命令并在之后使用输出,为此我使用 Gio.Subprocess 就像它在这个 wiki 中使用的那样:https://wiki.gnome.org/AndyHolmes/Sandbox/SpawningProcesses

目前,我有一个像这样的带有一些参数的参数:"ProgramXYZ -a -bc",我将其作为参数向量 argv 作为 ['ProgramXYZ'、'-a'、'-bc'] 传递。这个案例很好用。

假设我想调用两个程序并将输出与您的方法结合起来,例如:"ProgramXYZ -a -bc && ProgramB"。我的当前输出在普通终端中是正确的,但我不确定如何将它传递给 Gio.Subprocess。 ['ProgramXYZ','-a','-bc','&&','ProgramB'] 之类的东西不起作用,有没有办法实现它,还是我必须进行两次单独的调用?

抱歉,我还没有完成该页面(这就是它在我的沙盒中的原因)。

这是 运行 子流程的 Promise 包装器:

function execCommand(argv, input = null, cancellable = null) {
    let flags = Gio.SubprocessFlags.STDOUT_PIPE;

    if (input !== null)
        flags |= Gio.SubprocessFlags.STDIN_PIPE;

    let proc = new Gio.Subprocess({
        argv: argv,
        flags: flags
    });
    proc.init(cancellable);

    return new Promise((resolve, reject) => {
        proc.communicate_utf8_async(input, cancellable, (proc, res) => {
            try {
                resolve(proc.communicate_utf8_finish(res)[1]);
            } catch (e) {
                reject(e);
            }
        });
    });
}

现在你有两个合理的选择,因为你有一个很好的包装器。

我自己更喜欢这个选项,因为如果我启动顺序进程,我可能想知道哪个失败了,错误是什么等等。我真的不会担心额外的开销,因为第二个进程只有在第一个成功时才会执行,此时第一个进程将被垃圾回收。

async function dualCall() {
    try {
        let stdout1 = await execCommand(['ProgramXYZ', '-a', '-bc']);
        let stdout2 = await execCommand(['ProgramB']);
    } catch (e) {
        logError(e);
    }
}

另一方面,如果您真的想做 shell 事情,没有什么可以阻止您启动子 shell。最终你只是将相同的行为卸载到 shell,不过:

async function shellCall() {
    try {
        let stdout = await execCommand([
            '/bin/sh',
            '-c',
            'ProgramXYZ -a -bc && ProgramB'
        ]);
    } catch (e) {
        logError(e);
    }
}