I want to execute a system command (git clone) and stream the output to the user through a channel in Phoenix?
Can I somehow make System.cmd stream the results instead of waiting until it's done?
Or, can I write the output to a file and stream the content from there, as it's being appended?
You can use the popen and pclose functions to pipe to and from processes. The popen() function opens a process by creating a pipe, forking, and invoking the shell. We can use a buffer to read the contents of stdout and keep appending it to a result string and return this string when the processes exit.
Get output from shell command using subprocessLaunch the shell command that we want to execute using subprocess. Popen function. The arguments to this command is the shell command as a list and specify output and error. The output from subprocess.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
You can get the output after running a script using a pipe. We use pipes when we want the output of the child process. So here is the script, which you want to run. Put it in a command variable with the arguments your script takes (nothing if no arguments).
I would advice on using Porcelain for this. Specifically check https://github.com/alco/porcelain#messages.
You can use Porcelain.spawn_shell
to run your command with the out: {:send, self()}
option and implement matching handle_info
callbacks.
It is possible to override output with:
System.cmd "git", ["clone", "YOUR_GIT"], into: IO.stream(:stdio, :line)
Result:
Cloning into 'YOUR_GIT'... remote: Counting objects: 1665, done. remote: Compressing objects: 0% (1/979) remote: Compressing objects: 100% (979/979), done. Receiving objects: 0% (1/166remote: Total 1665 (delta 855), reused 1331 (delta 597) Receiving objects: 92% (Receiving objects: 100% (1665/1665), 5.25 MiB | 376.00 KiB/s, done. Resolving delResolving deltas: 100% (855/855), done. Checking connectivity... done.
{%IO.Stream{device: :standard_io, line_or_bytes: :line, raw: false}, 0}
docs
To help you achieve your specific task, redirecting the local standard stream into external one, there's a library porcelain, which handles it perfectly.
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