在同一实例

时间:2016-11-08 02:42:50

标签: python python-3.x

我正在寻找一种在同一个shell实例中执行多个命令的方法,每个命令使用一个单独的函数,我可以在shell进程打开/关闭时定义,并且可以将命令传递给。 到目前为止,我发现的所有答案都只出现在一个函数中

即:

#!/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)

我需要相同的效果,但每个命令都在不同的功能中,如

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

如果您想知道为什么它必须分开,运行命令来自用户输入。是的,我意识到这是一个安全风险,但在这种情况下安全性不是问题,因为它纯粹是一种教育风险,不会用于任何事情

2 个答案:

答案 0 :(得分:0)

您可以将subprocess.check_call(cmds_str, shell=True)与同一行中的多个命令结合使用:How to run two commands in one line in Windows CMD?

您可以单独构建每个命令并将其添加到列表中,然后使用' & '.join(cmd_list)获取cmds_str

答案 1 :(得分:0)

我不使用Windows,但它适用于Linux。

您可以使用pexpect

尝试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)

它运行cmd.exe,在child.sendline()中发送命令并查找提示child.expect_exact("> ")以获取命令child.before生成的所有文本。

相关问题