如何在 Swift 可执行文件中 运行 和打印 zsh 命令(如 "vi")
How to run and print zsh commands in Swift Executables (like "vi")
我需要 运行 在 Swift 中创建的 CLI 中需要动态输出的命令。我试过 ShellOut and other suggestions on Stack Overflow 之类的东西,但它们会在命令完成后打印输出,而不是在执行过程中。
我所希望的是 C++ 中的 system("vi README.md")
之类的东西,它将 运行 命令并在运行时打印输出。
没有它,vi
打印 Vim: Warning: Output is not to a terminal
然后留下黑屏并且无法退出命令。
事实证明,您可以在 Swift!
中使用 C++ 的 system()
函数
首先,我在我的包中创建了一个新目标(以解决过去的语言混合错误):
.target(name: "CBridge", dependencies: []),
然后,在目标的源文件夹中,我放入以下文件:
CBridge.cpp
include/CBridge.h
include/CBridge-Bridging-Header.h
CBridge.cpp
#include "include/CBridge.h"
#include <iostream>
using namespace std;
void shellCMD(const char *cmd) {
system(cmd);
}
CBridge.h
#ifdef __cplusplus
extern "C" {
#endif
void shellCMD(const char *cmd);
#ifdef __cplusplus
}
#endif
CBridge-桥接-Header.h
#include "CBridge.h"
只需调用 shellCMD(command)
它就会 运行 它,就像 'system(command)'!
我需要 运行 在 Swift 中创建的 CLI 中需要动态输出的命令。我试过 ShellOut and other suggestions on Stack Overflow 之类的东西,但它们会在命令完成后打印输出,而不是在执行过程中。
我所希望的是 C++ 中的 system("vi README.md")
之类的东西,它将 运行 命令并在运行时打印输出。
没有它,vi
打印 Vim: Warning: Output is not to a terminal
然后留下黑屏并且无法退出命令。
事实证明,您可以在 Swift!
中使用 C++ 的system()
函数
首先,我在我的包中创建了一个新目标(以解决过去的语言混合错误):
.target(name: "CBridge", dependencies: []),
然后,在目标的源文件夹中,我放入以下文件:
CBridge.cpp
include/CBridge.h
include/CBridge-Bridging-Header.h
CBridge.cpp
#include "include/CBridge.h"
#include <iostream>
using namespace std;
void shellCMD(const char *cmd) {
system(cmd);
}
CBridge.h
#ifdef __cplusplus
extern "C" {
#endif
void shellCMD(const char *cmd);
#ifdef __cplusplus
}
#endif
CBridge-桥接-Header.h
#include "CBridge.h"
只需调用 shellCMD(command)
它就会 运行 它,就像 'system(command)'!