简体   繁体   中英

Util.spawnCommandLine does not work on GNOME Shell extension

I'm writing an extension for GNOME Shell to check whether VPN is connected with this command:

ifconfig -a | grep tun

This is my extension.js file:

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);
}

Tried these and none of them worked:

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();

What should I do to execute that command and get the result?

I guess there's a couple ways you could do this. I would generally prefer GSubprocess for my subprocess spawning, but you could use GLib.spawn_command_line_sync() too:

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
}

If you really want to use grep for some reason, you could do this:

let [ok, out, err, exit] = GLib.spawn_command_line_sync('/bin/bash -c "ifconfig -a | grep"');

if (out.length > 0) {
    // Do stuff
}

Just remember that most of these functions will return a Uint8Array . GSubprocess on the other hand has functions that can communicate in UTF-8 with a subprocess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM