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

看板Python作者 (眾生都是未來佛)時間9年前 (2016/07/25 09:07), 9年前編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《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://www.ptt.cc/bbs/Python/M.1469408839.A.61A.html ※ 編輯: zxvc (140.115.73.148), 07/25/2016 09:20:31

07/25 13:03, , 1F
可以直接用 cmd.communicate(input="....") 就好
07/25 13:03, 1F
※ 編輯: zxvc (140.115.73.148), 07/25/2016 14:48:59
文章代碼(AID): #1NbMP7OQ (Python)
討論串 (同標題文章)
文章代碼(AID): #1NbMP7OQ (Python)