Skip to content

Instantly share code, notes, and snippets.

@singularitti
Last active July 13, 2023 23:28
Show Gist options
  • Select an option

  • Save singularitti/ab3a7ac060e79dda6a88f58d7657e63f to your computer and use it in GitHub Desktop.

Select an option

Save singularitti/ab3a7ac060e79dda6a88f58d7657e63f to your computer and use it in GitHub Desktop.
Read from and write to subprocess simultaneously in Julia #Julia #process
# 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"
@singularitti
Copy link
Author

singularitti commented Oct 17, 2019

equivalent to Python code

# Referenced from https://tkf.github.io/julia-python-snippets/dev/miscellaneous/#Read-from-and-write-to-subprocess-simultaneously-1
import sys

if sys.version_info >= (3, 5):
    from subprocess import run, PIPE
    output = run(["cat"], stdout=PIPE, input="hello", universal_newlines=True).stdout
else:
    from subprocess import Popen, PIPE
    proc = Popen(["cat"], stdout=PIPE, stdin=PIPE, universal_newlines=True)
    output, _ = proc.communicate("hello")

assert output == "hello"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment