I would like to execute a command (like ls) in Vala, like the Python os.system function, or, better, the popen function. Any idea ?
Let's first create a new Python file called shell_cmd.py or any name of your choice. Second, in the Python file, import the os module, which contains the system function that executes shell commands. system() function takes an only string as an argument. Type whatever you want to see as an output or perform an action.
The Linux exec command executes a Shell command without creating a new process. Instead, it replaces the currently open Shell operation. Depending on the command usage, exec has different behaviors and use cases.
OK, got it : Glib.Process.spawn_command_line_sync.
It's best to use the package posix
.
Then, just do Posix.system("command")
which returns an int.
http://www.valadoc.org/posix/Posix.system.html
You can use the GLib.Process.spawn_command_line_sync as:
public static int main (string[] args) {
string ls_stdout;
string ls_stderr;
int ls_status;
try {
Process.spawn_command_line_sync ("ls",
out ls_stdout,
out ls_stderr,
out ls_status);
// Output: <File list>
print ("stdout:\n");
// Output: ````
print (ls_stdout);
print ("stderr:\n");
print (ls_stderr);
// Output: ``0``
print ("Status: %d\n", ls_status);
} catch (SpawnError e) {
print ("Error: %s\n", e.message);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With