Can’t get the expected output of “dir” command using wexpect
on python.
My wexpect script:
import wexpect
def run_cmd():
# Start cmd.exe process
cmd = wexpect.spawn("cmd.exe")
# Display the initial prompt
cmd.expect(">")
print(cmd.before + ">", end="")
while True:
# Read user input
user_input = input()
# Exit loop if user types "exit"
if user_input.lower() == "exit":
cmd.sendline("exit")
break
# Send the user input to cmd.exe
cmd.sendline(user_input+" && (echo commandend1 && echo commandend2) || (echo commandend1 && echo commandend2)")
# Wait for the command to complete and print its output
cmd.expect(r"(commandend1 rncommandend2rnrn(?:[^\]+\)*[^\]*>)")
# Remove the first line of command output (user input)
print("rn".join(cmd.before.split("rn")[1:]))
prompt = cmd.after.replace("commandend1 rncommandend2rnrn", "")
print(prompt, end="")
if __name__ == "__main__":
run_cmd()
The expected output of my script (exactly the same as cmd.exe
):
Microsoft Windows [Version 10.0.22631.3810]
(c) Microsoft Corporation. All rights reserved.
C:UsersvIIr>dir
Volume in drive C is Acer
Volume Serial Number is C226-92AB
Directory of C:UsersvIIr
2024/06/30 下午 07:15 <DIR> .
2023/10/07 下午 11:43 <DIR> ..
2024/03/27 下午 08:43 <DIR> .arduino-create
2024/03/28 下午 01:23 <DIR> .arduinoIDE
2024/04/24 下午 04:51 <DIR> .cache
...
2024/06/21 下午 07:00 <DIR> Videos
16 File(s) 39,531,783 bytes
27 Dir(s) 21,730,820,096 bytes free
C:UsersvIIr>
The output of my script:
Microsoft Windows [Version 10.0.22631.3810]
(c) Microsoft Corporation. All rights reserved.
C:UsersvIIr>dir
Volume in drive C is Acer
Volume Serial Number is C226-92AB
Directory of C:UsersvIIr
2024/07/03 上午 10:56 <DIR> .2023/10/07 下午 11:43 <DIR> ..2024/03/27 下午 08:43 <DIR> .arduino-create2024/03/28 下午 01:23 <DIR>...2024/06/21 下午 07:00 <DIR> Videos 16 File(s) 35,370,247 bytes
27 Dir(s) 20,507,512,832 bytes free
C:UsersvIIr>