-1

I'm trying to undestand how input works.

Given for example a simple function like:

def f():
    s = input()
    print(s)

There's a way to call f and make it print something without building pipelines?

Obviously without typing anything into the termimal.

Rik Poggi
  • 28,332
  • 6
  • 65
  • 82

4 Answers4

2

One way of doing it would be to temporarily redefine sys.stdin.

eg:

import sys
from StringIO import StringIO

input_text = 'whatever you want the function to read from input()'

old_stdin = sys.stdin
#Reassign stdin to a StringIO object
sys.stdin = StringIO(input_text)

f()

sys.stdin = old_stdin
Shawabawa
  • 2,499
  • 1
  • 15
  • 17
1

Yes, executing a second python shell in a subprocess is the only way to give input to input (Unless you want to redefine input in the module).

Instead, you should read from an arbitrary file (and make the default sys.stdin). Then, you can simply set a different file - either a temporary one on disk, or a file-like StringIO object.

import sys,StringIO
def f(inputfile=sys.stdin):
    s = inputfile.readline()
    print(s)

# To test, call it like this:
f(StringIO.StringIO('testdata\n'))
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I'm not sure I understand what you're saying. Can you explain what you mean by reading from an arbitrary file, make the default `sys.stdin` and then setting a different file? – Rik Poggi Jan 12 '12 at 14:02
  • @RikP. Added demo code. Which part of the sentence is not clear to you? – phihag Jan 12 '12 at 14:33
  • Now I understand what you meant, thank you! I was trying to understand how `input` works, but your example was helpful anyway. – Rik Poggi Jan 12 '12 at 14:39
0

Not that I would necessarily recommend this solution, but you could rebind input to a different function...

NPE
  • 486,780
  • 108
  • 951
  • 1,012
-1

You can't provide a default text to input().

But if you use Linux and Bash, you can do something like this:

import readline

def rlinput(prompt, prefill=''):
   readline.set_startup_hook(lambda: readline.insert_text(prefill))
   try:
      return raw_input(prompt)
   finally:
      readline.set_startup_hook()

rlinput("Do you want to delete all files?  ", "yes")

(modified from this SO-answer).

See also:

Community
  • 1
  • 1
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • Wouldn't this require to press enter? – Rik Poggi Jan 12 '12 at 13:54
  • Why is it required to use bash here? – glglgl Jan 12 '12 at 14:17
  • @RikP.: You need to press enter to finish your input. How would you like to submit it else? glglgl: I didn't use other shells. I guess it might work with almost every shell, but it didn't work with the gedits "Better Python Console". As I didn't test it in more shells I just wanted to note that it might not work. – Martin Thoma Jan 12 '12 at 14:47