How to run a shell script without having to press

2019-09-01 05:06发布

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?

2条回答
看我几分像从前
2楼-- · 2019-09-01 05:44

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
查看更多
混吃等死
3楼-- · 2019-09-01 05:45

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"])
查看更多
登录 后发表回答