0

I'm currently writing a shell script which is interfacing with numerous python scripts. In one of these Python scripts I'm calling grass without starting it explicitly. When I run my shell script I have to hit enter at the point where I call grass (this is the code I got from the official working with grass page):

startcmd = grass7bin + ' -c ' + file_in2 + ' -e ' + location_path 
print startcmd
p = subprocess.Popen(startcmd, shell=True, 
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
 if p.returncode != 0:
    print >>sys.stderr, 'ERROR: %s' % err
    print >>sys.stderr, 'ERROR: Cannot generate location (%s)' % startcmd
    sys.exit(-1)
else:
    print 'Created location %s' % location_path
gsetup.init(gisbase, gisdb, location, mapset)

My problem is that I want this process to run automatically without me having to press enter everytime in between! I have already tried numerous options such as pexpect, uinput (doesn't work that well because of problems with the module). I know that in windows you have the msvcrt module, but I am working with linux... any ideas how to solve this problem?

tiago
  • 22,602
  • 12
  • 72
  • 88
RuM
  • 1
  • 1
  • 1
    White `\n` to stdin? – Klaus D. Nov 26 '14 at 10:05
  • Indeed you could try sending a newline to stdin of the process or you could try closing the stdin of the process entirely if you don't need it. – Etan Reisner Nov 26 '14 at 10:10
  • yes I have already tried adding /n and also /r/n but that just displayed empty lines in my console and did not activate the following process. But maybe I have set the term at the wrong place..where exactly would you place it in the code I posted? – RuM Nov 26 '14 at 11:25

2 Answers2

0

Use the pexpect library for expect functionnality.

Here's an example of interaction with a an application requiring user to type in his password:

child = pexpect.spawn('your command')
child.expect('Enter password:')
child.sendline('your password')
child.expect(pexpect.EOF, timeout=None)
cmd_show_data =  child.before
cmd_output = cmd_show_data.split('\r\n')
for data in cmd_output:
    print data
zfou
  • 891
  • 1
  • 10
  • 33
  • yes I have already tried that. but what kind of command am I supposed to spawn? my whole script? – RuM Nov 26 '14 at 11:58
0

I finally found an easy and fast way for simulating a key press:

just install xdotool and then use the following code for simulating e.g. the enter key:

import subprocess
subprocess.call(["xdotool","key","Return"])
RuM
  • 1
  • 1