shell - python如何实现在一个脚本里的多次交互?
黄舟
黄舟 2017-04-18 09:30:31
0
1
794

万恶的主管要求写一个针对于阿里云服务器的自动挂载的脚本,其实这种脚本不难,网上找找随便都有,但是比较恶心的是,主管非要求要用python去写,美其名曰“可读性强”。

于是本菜鸟为了绩效就开始写,但是写着写着就到了一个窘境,因为在 fdisk /dev/vdb的时候,是需要连续输入:“n p 1 回车 回车 p w ” 这六个信息需要反馈给系统才能顺利的分区,要是一次交互,到还好办,但是这样一次性要多次交互怎么破?难道必须要用pexpect去实现吗?

使用 os.system("fisk /dev/xvdb << End
n
p
1

p
w
End")
频频报错
本菜鸟环境是python 2.6.6

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
Peter_Zhu

Just use subprocess. For example, the following program requires input of name and age:

print 'what is your name?'
name = raw_input()
print 'your name is ' + name
print 'what is your age?'
age = raw_input()
print 'your age is ' + age

We can call the above program by interactively inputting John and 20 as follows:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['python', 'func.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
output = p.communicate(input='John\n20\n')
// print output

StackOverflow has many such questions!
Interactive input/output using python
Python subprocess and user interaction
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template