[英]Util.spawnCommandLine does not work on GNOME Shell extension
我正在為 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();
我應該怎么做才能執行該命令並獲得結果?
我想有幾種方法可以做到這一點。 我通常更喜歡GSubprocess
來生成子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 與子進程通信的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.