Gnome shell扩展:如何使用管道运行命令 [英] Gnome shell extensions: how to run a command with pipes

查看:140
本文介绍了Gnome shell扩展:如何使用管道运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在进行Gnome Shell扩展。我希望能够用管道运行一些命令。 (该命令实际上是xrandr --query | awk'某事物',但这不是主题)

So I'm making a Gnome Shell extension. And I want to be able to run some command with a pipe. (The command is actually "xrandr --query | awk 'something'", but that is off topic)

所以,到目前为止我所做的是

So, what I have done so far is

GLib.spawn_async_with_pipes(null,
                            ['/usr/bin/xrandr', '--query', '|', 'awk...'], null,
                            GLib.SpawnFlags.DO_NOT_REAP_CHILD, null);

但它不起作用!
我找不到任何在带管道的gnome扩展中运行命令的例子。

But it doesn't work! I can't find any example of running a command in a gnome extensions with a pipe.

我是否必须写 |在命令中像我一样?

Do I have to write "|" in the command like I did ?

推荐答案

调用 spawn_async_with_pipes( )不会帮助你,因为它会为你提供一个带有stdin / stdout / stderr的可用管道的对象,而不是给你一个彼此管道的呼叫。
除了只调用一个shell实例并让它执行命令外,唯一的办法是坚持扩展本身,让GNOME使用临时文件和默认shell(如果它已经存在则覆盖自己)来处理所有内容。

calling spawn_async_with_pipes() isn't going to help you, as it gives you back an object with availlable pipes for stdin/stdout/stderr rather than giving you calls that are piped to one another. Except for just calling a shell instance and letting it execute commands, the only way is to stick to the extension itself, letting GNOME handle everything using a temp file and default shell (one that overwrites itself if it already exists).

对于示例代码,让我们像一样执行相同的操作。 grep -i js 可以在CLI上执行:

For the example code, lets do the same as journalctl | grep -i js would do on a CLI:

//Gio for File I/O and GLib for command execution
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
//Create an object for the temp file
let file = Gio.file_new_tmp(null);
//Now write the output of journalctl to the file
file[1].get_output_stream().write(GLib.spawn_command_line_sync("journalctl")[1], null);
//Execute the command and save the result, this locks the thread though,
//so don't use indefinite commands like journalctl -f
//This returns [Boolean success, String stdout, String stderr, Number exit_status]
let journalJS = GLib.spawn_command_line_sync('grep -i js ' + file[0].get_path())[1]

现在随意处理您拥有的数据,因为一切都在命令完成后退出。

Now feel free to do with the data you have, as everything exits after the command is finished.

不要忘记使用 file [1] .close(); 关闭文件并将任何剩余变量设置为 null 完成后。

Don't forget to close the file using file[1].close(); and setting any remaining variables to null when finished.

这篇关于Gnome shell扩展:如何使用管道运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆