Python3: Using input() with stdin, like in hackerrank - python

I have an input file ("abc.in") which I will like to read each line as input(), exactly like how it works on hackerrank and other online coding platforms.
I have seen solutions replicating the same functionality by piping, fileinput and sys etc. On hackerrank I can just use input() to store one line of the input file as a variable. How do I do that locally? Do I store the files in the same place, what command do I use to run this in the terminal?
I thought this would be easy, but somehow I can't seem to figure out how to do it after trying for some time. Apologies if the answer was obvious.
Any help provided is greatly appreciated!

You can redirect the stdin with < on command line. Let's say you have following input stored to file data.in:
line1
line2
And you have following code stored to test.py:
print(1, input())
print(2, input())
Then you can run the script with redirected stdin:
~$ python3 test.py < data.in
1 line1
2 line2
If you want to save the output to a file you can redirect stdout as well:
~$ python3 test.py < data.in > data.out

Related

how to I redirect both code file and terminal output to the same output file (simulating python repl)?

I would like to save the input code and the output result into a file. For example the following python code code.py:
print(2+2)
print(3+2)
to create a code-and-output.txt:
>>> print(2+2)
4
>>> print(3+2)
5
But I can not get it working. Basically, I want to code-and-output.txt to capture what would happen if I run interpreted python and run statements in python interactive environment (code + output).
Ways that I have tried so far:
Redirect stdout:
python code.py > code-and-output.txt
It only saves the output.
Redirect stdout and stdin:
python < code.py > code-and-output.txt
It does the same (only output).
nohup
nohup python code.py
The same problem: only output.
Script
script -q code-and-output.txt
python
print(2+2)
print(2+3)
ctr+d
ctr+d
It works but I need to do it manually. Moreover, it saves some garbage that I can not make them quiet with -q.
Bash Script
# bash-file.sh
python &
print(2+2)
print(2+3)
Does not work: commands run in console bash, not python. It does not work with & either: never ends python repl.
Using tty
open another terminal like /dev/pts/2 and send above bash-file.sh
cat bash-file.sh > /dev/pts/2
It just copies but does not run.
I am not interested in solutions like Jupyter and iPython. They have their own problems that does not address my requirement.
Any solution through linux commands (preferably) or python? Thank you.
Save this is as repl_sim.py in the same directory as your code.py:
with open("code.py", 'r') as input_file:
for line in input_file:
print(f">>> {line.strip()}")
eval(line)
Then run in your terminal with the following if you want to redirect the output to a text file named code-and-output.txt:
python repl_sim.py > code-and-output.txt
-OR-
Then run in your terminal with the following if you want to see the output as well as the make the text file matching:
python repl_sim.py | tee code-and-output.txt
It at least works for the example you provided as code.py.
Pure Python version of first option above so that you don't need shell redirect.
Save this code as repl_sim.py:
import contextlib
with open('code-and-output.txt', 'w') as f:
with contextlib.redirect_stdout(f):
with open("code.py", 'r') as input_file:
for line in input_file:
print(f">>> {line.strip()}")
eval(line)
Then run in your terminal with:
python repl_sim.py
That will result in code-and-output.txt with your desired content.
Contextlib use based on Raymond Hettinger's August 17th 2018 Tweet and contextlib.redirect_stdout() documentation
.

sys.stdin in python on unix shell

I am writing a python program through a unix shell. While I have written the program, I had to hard code my data in. However my goal is to be able to be able to stdin the data through the shell like this
python3 sample.py data.txt
Where sample.py is the program and data.txt is the data. Data.txt contains two column of data seperated by a tab. Then I have print to make sure it is working. The way I wrote the code to read the data in is as follows
for line in sys.stdin:
words = re.split(r'\t',line)
print(words)
Splitting the content of the lines the tab, and printing to make sure it is working. When running line "python3 sample.py data.txt", it does nothing, however the program will not exit like there is an infinite loop or something. How can I get this to print?
With
python3 sample.py data.txt
you are passing data.txt as an argument. To pass its content as input (to stdin), do:
python3 sample.py < data.txt
The redirection operator < is a shell construct and refers to the stdin.

How to (using console) put results in a txt. file or get complete results from a code that has already runned

i'm currently solving optimization problems with python. One problem takes about 5hrs to solve which result will appear (sadly) in console but not completely since it's a very big list. I'm wondering right now if there is anyway to get the solution of the list completely while i'm waiting for the results (i've been waiting for 4hrs. now).
If there is a way i can get the complete result in the console after the code has runned, let me know.
If there is a way via console to put the results in a .txt file or any type of readable file afterwards please let me know.
If there is no solution to this problem, let me know.
Thanks alot.
say your script is called yourscript.py
and you have been running it in the console with: python yourscript.py
if you use this command:
python yourscript.py > newfile.txt
all of the output will go into newfile.txt
Suppose your python file is myfile.py, in order to redirect what is printed in this file run your file as:
python myfile.py > myfile.txt
Your printed list will be printed in myfile.txt.
pipe it into a file with the format you want
for example your file name is xyz.py
In your python shell
python xyz.py > myfile.txt
Your output will now be in myfile.txt

Syntax for input redirection in IDLE

I need to enter the contents of a text (.txt) file as input for a Python (.py) file. Assuming the name of the text file is TextFile and the name of the Python file PythonFile, then the code should be as follows:
python PythonFile.py < TextFile.txt
Yet, when I try to do this in IDLE and type in
import PythonFile < TextFile,
IDLE gives me an invalid syntax message, pointing to the < sign. I tried all sorts of variations on this theme (i.e.,using or not using the file name extensions), but still got the same invalid-syntax message. How is the syntax different for input redirection in IDLE?
If it works in the command line, then why do you want to do this in IDLE? There are ways to achieve a similar result using, for example, subprocess, but a better way would be to refactor PythonFile.py so that you can call a function from it, e.g.:
>>> import PythonFile
>>> PythonFile.run_with_input('TextFile.txt')
If you post the contents of PythonFile.py, we might be able to help you do this.

Python and Bash: how to automate user input?

I downloaded some scripts in both python and bash that prompt the user for command line input. Since I run these scripts often, I would like to automatically supply the input to the programs. I prefer not to modify the scripts. Is there a way to do it without modifying the original code?
[UPDATE] thanks to EnabrenTane's advice, it seems to work pretty well, until I got to a line that read password = getpass.getpass('password: '). It complains the following:
File "/usr/lib/python2.4/getpass.py", line 29, in unix_getpass
old = termios.tcgetattr(fd) # a copy to save
termios.error: (25, 'Inappropriate ioctl for device')
Any way to get around that?
Like this on bash: $ ./python_script < input.txt
edit:
Alternatively you could write your scripts to take ARGV as a file name to read from. You could reopen STDIN to the file and not have to change any other lines.
Since the responses in via stdin:
cat answers | yourscript.py
Due to the password requirement, I ended up using pexpect, a python module that automates user input.

Categories