Last active
July 13, 2023 23:28
-
-
Save singularitti/ab3a7ac060e79dda6a88f58d7657e63f to your computer and use it in GitHub Desktop.
Read from and write to subprocess simultaneously in Julia #Julia #process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Referenced from https://tkf.github.io/julia-python-snippets/dev/miscellaneous/#Read-from-and-write-to-subprocess-simultaneously-1 | |
| function communicate(cmd::Cmd, input) | |
| inp = Pipe() | |
| out = Pipe() | |
| err = Pipe() | |
| process = run(pipeline(cmd, stdin=inp, stdout=out, stderr=err), wait=false) | |
| close(out.in) | |
| close(err.in) | |
| stdout = @async String(read(out)) | |
| stderr = @async String(read(err)) | |
| write(inp, input) | |
| close(inp) | |
| wait(process) | |
| return ( | |
| stdout = fetch(stdout), | |
| stderr = fetch(stderr), | |
| code = process.exitcode | |
| ) | |
| end | |
| # Usage | |
| # @assert communicate(`cat`, "hello").stdout == "hello" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
equivalent to Python code