【问题标题】:Util.spawnCommandLine does not work on GNOME Shell extensionUtil.spawnCommandLine 不适用于 GNOME Shell 扩展
【发布时间】:2020-04-04 05:50:44
【问题描述】:

我正在为 GNOME Shell 编写一个扩展来检查 VPN 是否与此命令连接:

ifconfig -a | grep tun

这是我的 extension.js 文件:

const St = imports.gi.St;
const Main = imports.ui.main;
const Mainloop = imports.mainloop;

let panelOutput, panelOutputText, timeout;

function panelOutputGenerator(){

    // I want to execute this command here and get the result:
    // 'ifconfig -a | grep tun'
    let commandResult = 'string of result that terminal is returned';       

    let connectionStatus = (commandResult!='')? 'VPN is Enabled' : 'Normal';

    panelOutputText.set_text(connectionStatus);

    return true;
}

function init(){

    panelOutput = new St.Bin({
        style_class: 'panel-button',
        reactive: true,
        can_focus: false,
        x_fill: true,
        y_fill: false,
        track_hover: false
    });
    panelOutputText = new St.Label({
        text: 'Normal',
        style_class: 'iceLabel'
    });
    panelOutput.set_child(panelOutputText);
}

function enable(){

    Main.panel._rightBox.insert_child_at_index(panelOutput,0);
    timeout = Mainloop.timeout_add_seconds(1.0,panelOutputGenerator);
}

function disable() {

    Mainloop.source_remove(timeout);
    Main.panel._rightBox.remove_child(panelOutput);
}

尝试了这些,但都没有奏效:

const Util = imports.misc.util;
let commandResult = Util.spawn(['/bin/bash', '-c', "ifconfig -a | grep tun"]);
const Util = imports.misc.util;
let commandResult = Util.spawnCommandLine('ifconfig -a | grep tun');
const GLib = imports.gi.GLib;
let [res, out] = GLib.spawn_sync(null,['ifconfig','-a','|','grep','tun'],null,null,null);
et commandResult = res.toString();

我应该怎么做才能执行该命令并获得结果?

【问题讨论】:

    标签: javascript linux gnome gnome-shell-extensions


    【解决方案1】:

    我想有几种方法可以做到这一点。我通常更喜欢GSubprocess 来生成子进程,但您也可以使用GLib.spawn_command_line_sync()

    const ByteArray = imports.byteArray;
    const GLib = imports.gi.GLib;
    
    let [ok, out, err, exit] = GLib.spawn_command_line_sync('ifconfig -a');
    
    if (ByteArray.toString(out).includes('tun')) {
        // Do stuff
    }
    

    如果你出于某种原因真的想使用grep,你可以这样做:

    let [ok, out, err, exit] = GLib.spawn_command_line_sync('/bin/bash -c "ifconfig -a | grep"');
    
    if (out.length > 0) {
        // Do stuff
    }
    

    请记住,这些函数中的大多数都将返回Uint8Array。另一方面,GSubprocess 具有可以 UTF-8 与子进程通信的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 2021-12-24
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多