1

I need to run commands that require dynamic output in my CLI made in Swift. I've tried things like ShellOut and other suggestions on Stack Overflow, but they print the output once the command is done, not while it is going.

What I'm hoping for is something like system("vi README.md") from C++, where it will run the command and print the outputs as it goes.

Without it, vi prints Vim: Warning: Output is not to a terminal then leaves a black screen and there is no way to exit the command.

Ben216k
  • 567
  • 4
  • 7
  • I don't know Swift, but I would assume the solution is actually independent of any particular shell. For example, in Python you would write `subprocess.run(["vi", "README.md"])`, with `vi` being executed directly, rather than starting a shell to execute `vi`. – chepner Jun 14 '20 at 13:08

1 Answers1

1

Turns out, you can use the system() function for C++ in Swift!

First, I created a new target in my package (to get past language mixing errors):

.target(name: "CBridge", dependencies: []),

Then, in the target's source folder, I put the following files:

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-Bridging-Header.h

#include "CBridge.h"

Simply call shellCMD(command) and it will run it, just like 'system(command)'!

Ben216k
  • 567
  • 4
  • 7