start cmd
seems to break wexpect, but if you only need a new shell, and not a new window, try this, as suggested by @furas and @D-E-N:
import wexpect
print("Wexpect Example:")
# Create the child process
child = wexpect.spawn("cmd.exe")
child.expect_exact(">")
# If you only expect a prompt after each command is complete, this should be fine
list_of_commands = ["tree",
"echo hi\n", ]
for c in list_of_commands:
child.sendline(c)
child.expect_exact(">")
print(child.before)
# Exit will close the child implicitly, but I add the explicit child.close() anyway
child.sendline("exit")
child.close()
print("Script complete. Have a nice day.")
Output
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\Rob\source\repos\Wexpect> python wexpect.py
Wexpect Example:
tree
Folder PATH listing for volume Windows-SSD
Volume serial number is XXXX-XXXX
C:.
├───folder1
├───folder2
│ ├───sub-folder2.1
│ └───sub-folder2.3
└───folder3
C:\Users\Rob\source\repos\Wexpect
echo hi
hi
C:\Users\Rob\source\repos\Wexpect
Script complete. Have a nice day.
PS C:\Users\Rob\source\repos\Wexpect>
For brevity, I skipped handling EOF and TIMEOUT errors. Check out the pexpect and wexpect documentation for more ideas.
Good luck coding!