How to execute a long bash sequence with a Python subprocess

I want to do this:

Bash code:

grub --batch << EOF
root (hd0,1)
find /boot/grub/menu.lst
setup (hd0)
quit
EOF

Python Code:

subprocess.call('grub --batch << EOF', shell=True)
subprocess.call('root (hd0,1)', shell=True)
subprocess.call('find /boot/grub/menu.lst', shell=True)
subprocess.call('setup (hd0)', shell=True)
subprocess.call('quit', shell=True)
subprocess.call('EOF', shell=True)

But that does not work. Is anyone now an alternative way to solve this?

Thank you so much!

+3
source share
2 answers

You can do something terrible, like:

subprocess.call('echo -e "root (hd0,1)\nfind /boot/grub/menu.lst\nsetup (hd0)\nquit" | grub --batch', shell=True)

I am sure there is a better way to do this though.

+1
source

The solution is to send the script as a single line:

script = '''
root (hd0,1)
find /boot/grub/menu.lst
setup (hd0)
quit
'''
print subprocess.Popen('grub', stderr=subprocess.STDOUT).communicate(script)[0]

shell=True not required.

+5
source

All Articles