作者zxvc (众生都是未来佛)
看板Python
标题Re: [问题] 如何在shell里面下指令
时间Mon Jul 25 09:07:16 2016
※ 引述《proX (不知名水鸟)》之铭言:
: 嗨大家好
: 想请问如何要在一个新的shell里面下指令,不会等到该shell关闭以後才能继续那个指令
: 举个例子,在Unix shell上面,假设用特定的指令会开新的shell (暂且称之为newsh),
: 进去这个newsh shell以後,想要用exit再出去,也就是回去原本的unix shell
: enter_shell = subprocess.Popen('newsh', shell=True)
: exit_shell = subprocess.Popen('exit', shell=True, stdout=subprocess.PIPE)
: out, _ = exit_shell.communicate()
: print out
:
: enter_shell成功进去newsh以後,exit_shell起不了作用。
: 试着在 command line 上面打'exit'可以结束newsh,而exit_shell这时候突然可以动了,
: 因为执行exit_shell又exit一次,但terminal并没有被关闭,之後out才跟着被印出来
: 但我希望的是exit_shell的程序在newsh里面执行,而不是等待newsh shell关闭以後才
: 接收这个指令,变成exit两次,试了几次都失败,不知道要怎麽做QQ
: 有任何建议或其他作法都非常感谢~~~
: 谢谢大家!!
参考:
cmd = subprocess.Popen('bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
cmd.stdin.write(b'echo $SHELL\n')
cmd.stdin.flush()
cmd.stdin.write(b'tcsh\n')
cmd.stdin.flush()
cmd.stdin.write(b'echo $shell\n')
cmd.stdin.flush()
cmd.stdin.write(b'exit\n')
cmd.stdin.flush()
cmd.stdin.write(b'echo $SHELL\n')
cmd.stdin.flush()
cmd.stdin.write(b'exit\n')
cmd.stdin.flush()
cmd.stdout.readlines()
注意:
1. 每个写入指令都需'\n'结尾,这是给shell看的。
2. flush确切使用时机我不是很清楚,最保守作法是每个wirte後就flush一次,
读取时才不容易deadlock。
3. 最上层shell要exit,才会输出EOF。readlines才知道读取结束。
4. 要边写边读也可以,用readline。
--
楞严咒(附注音):
http://1drv.ms/1c0YbNt
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.115.73.148
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1469408839.A.61A.html
※ 编辑: zxvc (140.115.73.148), 07/25/2016 09:20:31
1F:推 kenduest: 可以直接用 cmd.communicate(input="....") 就好 07/25 13:03
※ 编辑: zxvc (140.115.73.148), 07/25/2016 14:48:59