如何使用Python子进程执行长bash序列

Jon*_*ira 3 python bash subprocess

我想这样做:

Bash代码:

grub --batch << EOF
root (hd0,1)
find /boot/grub/menu.lst
setup (hd0)
quit
EOF
Run Code Online (Sandbox Code Playgroud)

Python代码:

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)
Run Code Online (Sandbox Code Playgroud)

但这不起作用.现在有人解决这个问题的替代方法吗?

非常感谢!

Aar*_*lla 5

解决方案是将脚本作为一个字符串发送:

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

shell=True 不应该是必要的.


pis*_*lis 2

你可以做一些可怕的事情,比如:

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

我确信有更好的方法来做到这一点。