I thought that bytesavailable
would solve this issue (based on this), but I will demonstrate that it doesn’t work.
Say I have the following script:
println(bytesavailable(stdin))
Now I check how many bytes there are in a dummy file:
$ wc -c foo.txt
21 foo.txt
So piping this file into the Julia script show display 21, I thought—but it displays zero:
$ cat foo.txt | julia test.jl
0
Does anyone know how to detect if anything has been passed to the script via stdin
? The goal is to have something like this:
bytesavailable(stdin) > 0 ? println(read(stdin, String)) : println("No stdin given")
Thanks in advance!
1 Like
how about
s = readchomp(stdin) # chomp to remove trailing \n
isempty(s) ? println("No stdin given") : println(s)
?
read_chomp(stdin)
will block waiting for input if none is being piped in.
2 Likes
Cross-pasting from Slack…
It does seem like there should be an easier (and/or more readily apparent) way to do this. Part of the complexity seems to be that the type of stdin
is very dependent on how julia is started:
$ cat test.jl
using InteractiveUtils
println(supertypes(typeof(stdin)))
$ julia test.jl
(Base.TTY, Base.LibuvStream, IO, Any)
$ cat /dev/null | julia test.jl
(Base.PipeEndpoint, Base.LibuvStream, IO, Any)
$ julia test.jl < /dev/null
(IOStream, IO, Any)
For the IOStream
case, you could use poll_fd
from the FileWatching
package, but it doesn’t seem to work with Base.LibuvStream
types (at least not on 1.6.0 for me).
2 Likes