Python 的 Pexpect 模組 提供使用者能夠與互動的程式進行溝通:
而這裡的 JExpect 可以想像成Pexpect 模組 的 Java 版本, 並封裝到 Flib.jar 模組. 底下將針對該類別的使用進行介紹.
Usage Of JExpect
JExpect 上提供靜態方法 Spawn(String cmd) 讓你可以透過 Spawn 一個新的 Process 來執行給定命令:
- /**
- * BD: Spawn a Process by executing given command.
- *
- * @param cmd: Command to execute in Spawn process.
- * @return
- * @throws Exception
- */
- public static ISpawnProcess Spawn(String cmd) throws Exception
則你可以使用下面代碼啟動此互動程式, 並使用返回的 ISpawnProcess 介面的實作物件進行與程式互動:
- ISpawnProcess sp = JExpect.Spawn("java -jar HelloShell.jar")
- /**
- * Send input line to System.in.
- *
- * @param line: Line to be sent to System.in
- * @throws Exception
- */
- public void sendLine(String line) throws Exception;
- public Future
expect_asyn(String pattern) throws Exception; - public boolean expect_async(String pattern, int timeout) throws Exception;
- public boolean expect(String pattern, int timeout) throws Exception;
- public boolean expect(String pattern) throws Exception;
- public boolean expect_exact(String pattern, int timeout) throws Exception;
- public boolean expect_exact(String pattern) throws Exception;
- ISpawnProcess sp = JExpect.Spawn("java -jar HelloShell.jar")
- if(sp.expect_async("Hello Shell", 2000))
- {
- printf("\t[Info] Entering Interactive console...\n")
- }
- else
- {
- printf("\t[Error] Fail to open Interactive console!\n")
- sp.close() // Close Spawn Process
- }
- sp.sendLine("name")
- printf("\t[Info] Expect Name...\n")
- sp.expect("My name is", 2000)
- printf("\t${sp.lastExpect[-1]}\n")
- import flib.util.system.ISpawnProcess
- import flib.util.system.JExpect
- printf("\t[Info] Enter Interactive App...\n")
- ISpawnProcess sp = JExpect.Spawn("java -jar HelloShell.jar")
- printf("\t[Info] Expect Interactive...\n")
- sp.expect_async("Hello Shell", 2000)
- sp.sendLine("name")
- printf("\t[Info] Expect Name...\n")
- sp.expect_async("My name is", 2000)
- printf("\t${sp.lastExpect[-1]}\n")
- sp.sendLine("age")
- printf("\t[Info] Expect Age...\n")
- sp.expect_async("My age is", 2000)
- printf("\t${sp.lastExpect[-1]}\n")
- sp.sendLine("test")
- printf("\t[Info] Expect Error...\n")
- sp.expect_async("unknown", 2000)
- printf("\t${sp.lastExpect[-1]}\n")
- sp.sendLine("bye")
- printf("\t[Info] Expect Bye...\n")
- sp.expect_async("Bye", 2000)
- printf("\t${sp.lastExpect[-1]}\n")
- printf("\t[Info] Done...\n")
- sp.close()
- printf("\t[Info] Exit main...\n")
Supplement
* Flib - frequent-used-functionality
* [ Python 文章收集 ] python Pexpect
沒有留言:
張貼留言