有没有办法启动终端窗口(或 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
或terminal
(在 MacOS/Linux 上)窗口
open a new
cmd.exe
orterminal
(on MacOS / Linux) window
传递/运行命令,例如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/D C: est"
然后使用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
或 Ubuntu
的等效工作代码:
And here is the equivalent working code for Linux Mint Cinnamon
or 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屋!