views:

56

answers:

2

there is a script that expects keyboard input, i can call that script with os.system('./script') in python,

how is it possible to send back an input to the script from another calling script?

update:

the script is:

$ cat script
#!/usr/bin/python
for i in range(4):
        name=raw_input('enter your name')
        print 'Welcome %s :) ' % name

when i try without a for loop, it works but it shows the output only when the script quits.

>>> p = subprocess.Popen('./script',stdin=subprocess.PIPE)
>>> p.communicate('navras')
enter your nameWelcome navras :)

when i try it with the foor loop, it throws error, How to display the statements interactive as and when the stdout is updated with new print statements

>>> p.communicate('megna')
enter your nameWelcome megna :)
enter your nameTraceback (most recent call last):
  File "./script", line 3, in <module>
    name=raw_input('enter your name')
EOFError: EOF when reading a line
(None, None)
+1  A: 

You can use subprocess instead of os.system:

p = subprocess.Popen('./script',stdin=subprocess.PIPE)
p.communicate('command')

its not testet

Sven Walter
These references should give more detail:http://docs.python.org/library/subprocess.htmlhttp://jimmyg.org/blog/2009/working-with-python-subprocess.htmlIn the example above, you probably also want to add the argument `stdout=subprocess.PIPE`. The communicate function should return a tuple `(stdout, stderr)` with the data sent to each of these descriptors.You an also try `p.stdin.write()` and `p.stdout.readline()`. Really, you can treat `p.stdin` and `p.stdout` just as you would any other file object :)
Michael Mior
when i try it with the foor loop, it throws error, How to display the statements interactive as and when the stdout is updated with new print statements.>>> p.communicate('megna')enter your nameWelcome megna :)enter your nameTraceback (most recent call last): File "./script", line 3, in <module> name=raw_input('enter your name')EOFError: EOF when reading a line(None, None)
matt jack
A: 

In fact, os.system and os.popen are now deprecated and subprocess is the recommended way to handle all sub process interaction.

muckabout