有没有办法启动终端窗口(或Windows上的cmd)并传递/运行命令? [英] Is there a way to launch a terminal window (or cmd on Windows) and pass/run a command?
问题描述
是否可以执行以下操作?
Is it possible to do the following?
-
打开新的
cmd.exe
或终端
(在MacOS / Linux上)窗口
open a new
cmd.exe
orterminal
(on MacOS / Linux) window
通过/运行命令,例如 cd< path>
pass / run a command, e.g. cd <path>
我可以通过运行以下命令打开cmd:
I can open cmd by running this command:
"$electron.shell.openItem('cmd.exe')"
但是 shell.openItem
不允许传递参数/命令。
But shell.openItem
doesn't allow to pass the arguments / commands.
我尝试使用 child_process
,但我完全无法使用它,它不会打开新的终端窗口:
I tried using child_process
but I couldn't make it work at all, it doesn't open a new terminal window:
const { spawn, exec } = require('child_process');
spawn('C:/Windows/System32/cmd.exe');
我也尝试运行以下命令,但仍然没有执行任何操作:
I also tried running the following command, but still nothing:
spawn( 'cmd.exe', [ '/c', 'echo ASDASD' ], { stdio: [0, 1, 2] } )
我看到的唯一可能的解决方案是创建 command.bat
:
开始cmd.exe / K cd / DC:\test;
然后使用 openItem
:
"$electron.shell.openItem('command.bat')"
但这仅适用于Windows
But that would only work on Windows
推荐答案
这是一个工作示例,展示了如何从渲染器脚本在 macOS
上的特定路径(例如〜/ Desktop)上打开终端窗口。 :
Here is a working example showing how to open a Terminal window at a specific path (~/Desktop for instance) on macOS
, from a renderer script:
const { app } = require ('electron').remote;
const atPath = app.getPath ('desktop');
const { spawn } = require ('child_process');
let openTerminalAtPath = spawn ('open', [ '-a', 'Terminal', atPath ]);
openTerminalAtPath.on ('error', (err) => { console.log (err); });
应该很容易将其适应于任何选定的atPath ...
其他命令,我还没有找到方法...
It should be easy to adapt it to any selected atPath... As for running other commands, I haven't found a way yet...
这是 Linux Mint Cinnamon $ c的等效工作代码。 $ c>或
Ubuntu
:
const { app } = require ('electron').remote;
const terminal = 'gnome-terminal';
const atPath = app.getPath ('desktop');
const { spawn } = require ('child_process');
let openTerminalAtPath = spawn (terminal, { cwd: atPath });
openTerminalAtPath.on ('error', (err) => { console.log (err); });
请注意,终端应用程序的名称可能会有所不同,具体取决于Linux风格(例如 Linux Mint MATE
上的'mate-terminal'
),并且可以明确定义应用程序的完整路径,为了安全起见:
Please note that the name of the terminal application may be different, depending on the Linux flavor (for instance 'mate-terminal'
on Linux Mint MATE
), and also that the full path to the application can be explicitly defined, to be on the safe side:
const terminal = '/usr/bin/gnome-terminal';
HTH ...
这篇关于有没有办法启动终端窗口(或Windows上的cmd)并传递/运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!