Python 2's io.open does this as well, but the import takes a lot more space: $ python -c "from io import open open(1,'w').write(open(0).read())" < inputs.txt If this works on your system, it will shave off more characters. Since the file descriptors for stdin and stdout are 0 and 1 respectively, we can also pass those to open in Python 3 (not 2, and note that we still need the 'w' for writing to stdout). Golfed into a command: $ python -c "import sys (())" < inputs.txt Print it back out to make sure it looks right: $ python -c "import sys (())" < stdindemo2.pyĪnd redirecting the inputs into the file: $ python -m stdindemo2 < inputs.txt Say you have a file, inputs.txt, we can accept that file and write it back out: python -c "import sys (())" inputs.txtĪnd using the code we've already seen, we can check that we've created the file: $ python -c "import sys (())" stdindemo.pyĪnd let's print it back out to ensure it's as we expect: $ python -c "import sys (())" stdindemo2.py We can see that sys.stdin is in default text mode: > import sys You just need to read from sys.stdin, for example, if you pipe data to stdin: $ echo foo | python -c "import sys print(())" Quick sys.stdin examples compatible with Python 2 and 3, Windows, Unix Use like ''.join(fileinput.input()).īoth sys and fileinput must be imported, respectively, of course. fileinput.input() - returns an iterator over lines in all files listed in sys.argv, or stdin if not given.open('/dev/stdin').read() - similar to open(0), works on Python 2 and 3, but not on Windows (or even Cygwin).It returns a file-like object like sys.stdin - probably your best bet for golfing. open(0).read() - In Python 3, the builtin function open accepts file descriptors (integers representing operating system IO resources), and 0 is the descriptor of stdin.(Probably not great for golfing.) In Python 2, this is raw_input(prompt). You'd have to do this repeatedly to get more lines, at the end of the input it raises EOFError. input(prompt) - pass it an optional prompt to output, it reads from stdin up to the first newline, which it strips.sys.stdin - A file-like object - call () to read everything. I'm trying to do some of the code golf challenges, but they all require the input to be taken from stdin.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |