0

I am looking for a way to execute multiple commands in the same shell instance using a separate function for each, something that I can define when the shell process opens/closes and can pass commands to. so far all the answers I have found have only been in a single function

ie:

#!/usr/bin/env python
from subprocess import check_call

check_call(r"""set -e
ls -l
<some command> # This will change the present working directory 
launchMyApp""", shell=True)

I need the same effect but with each command in a different function like

shell.open()
shell.exec("dir")
shell.exec("cd C:/Users/" + User + "/Desktop)
shell.close()

if you are wondering whyyy it has to be separate the command to run is coming from user input. yes I realize that is a security risk, but security isn't a problem in this case, as its purely an educational venture and not going to be used for anything

  • you can try `pexpect` module and run `cmd.exe` and then you can send many commands to the same `cmd.exe` – furas Nov 08 '16 at 04:05

2 Answers2

0

you could use subprocess.check_call(cmds_str, shell=True) in conjunction with multiple commands in the same line: How to run two commands in one line in Windows CMD?

You could build each command individually and add them to a list, and then use ' & '.join(cmd_list) to get cmds_str.

Community
  • 1
  • 1
Bobby
  • 97
  • 7
  • It needs to be so user inputs command, command executes in shell, prints returned stuff, user inputs another command, command executes in the same shell, prints more returned stuff... pexpect would be perfect if the pexpect.spawn() and pexpect.expect() functions were windows compatible – TheBestNightSky Nov 08 '16 at 09:07
  • suppose I could simulate it being in the same shell by saving and rerunning every previous command in the new shell... but that seems very not python XD – TheBestNightSky Nov 08 '16 at 21:38
0

I don't use Windows but it works on Linux.

You can try pexpect with cmd.exe

import pexpect

child = pexpect.spawn("cmd.exe")

child.expect_exact("> ")
#print(child.before.decode('utf-8'))
print(child.before)

child.sendline("dir")
child.expect_exact("> ")
print(child.before)

child.sendline("cd C:/Users/" + User + "/Desktop")
child.expect_exact("> ")
print(child.before)

It runs cmd.exe, sends command in child.sendline() and looks for prompt child.expect_exact("> ") to get all text generated by command child.before.

furas
  • 134,197
  • 12
  • 106
  • 148
  • pexpect isn't entirely windows compatible.. .sendline() and .expect() arent available on windows and the site isn't clear as to if there is a windows version of them... – TheBestNightSky Nov 08 '16 at 05:34