Re: [問題] 如何在shell裡面下指令

作者: zxvc (眾生都是未來佛)   2016-07-25 09:07:16
※ 引述《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。
作者: kenduest (小州)   2016-07-25 13:03:00
可以直接用 cmd.communicate(input="....") 就好

Links booklink

Contact Us: admin [ a t ] ucptt.com