Reading from stdin
Hey everyone! Here's a github gist with a struct to read from stdin and a recreation of the Python input function. https://gist.github.com/thatstoasty/20752ad6fb1d97790c208c007792de4b
I was working on this snippet for the stdlib a month or two ago, but got held up figuring out how to add some clean tests where we read from stdin. The furthest I got was feeding stdin to one test, but then the subsequent ones failed. Maybe I'll return to it soon, but I figured people might get some use out of this for now π
Gist
Reading from stdin using mojo and recreating the Python input function
Reading from stdin using mojo and recreating the Python input function - stdin.mojo
12 Replies
have you considered making a PR to get this in the standard lib? We really should have
input
I developed this intending to open a PR into nightly, but got caught up with figuring out how to make the stdin input repeatable for tests.
I may just open the PR and look for some guidance from the stdlib team and/or maintainers.
This is glorious, thank you dude!
If you're sure you aren't reading from it, you can close the fd and then re-open it and stdin in R+W using /proc/self/fd/* on Linux.
Awesome @toasty this is very useful, if you're short on time raise a PR and I'll push some tests into it for you.
Just for latest nightly need to add this up the top:
Previously there was a bunch of things being imported unintentionally slowing things down, there is a prelude now: https://github.com/modularml/mojo/blob/nightly/stdlib/src/prelude/__init__.mojo
Awesome, I'd appreciate that. I have some tests written, but couldn't run more than one at a time. I'll clean up my feature branch and submit a PR sometime soon π
Any thoughts on where a struct like this should live? I defaulted to dropping it in sys like python, but would builtin.io be preferable?
io.input makes sense
Or possibly make it io.stdin and then have later on we can have a higher level input function which handles things like Locales properly.
Yeah
builtin/io.mojo
would be great, can add input
to the prelude __init__.mojo
as wellI opened up a PR to add the stdin struct and input function, any help on fixing up the tests would be awesome! π https://github.com/modularml/mojo/pull/3392
Thanks heaps just fixed up the one test for now, we can add to it later. Great to get this long requested feature in cheers.
Awesome, thatβs great to hear!
Just pulled in the latest version of nightly, I see the updates there!
Awesome, btw the nightly branch on
modularml/mojo
isn't being updated currently due to some teething issues with upgrades to the CI, but the nightly/mojo
package is still being updated