[英]Execute multiple shell/command prompt commands in same instance
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. 我正在寻找一种在同一个shell实例中为每个实例使用单独的函数执行多个命令的方法,我可以在shell进程打开/关闭并将命令传递给它时定义一些方法。 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 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? 您可以将
subprocess.check_call(cmds_str, shell=True)
与同一行中的多个命令结合使用: 如何在Windows CMD中的一行中运行两个命令?
You could build each command individually and add them to a list, and then use ' & '.join(cmd_list)
to get cmds_str
. 您可以分别构建每个命令并将它们添加到列表中,然后使用
' & '.join(cmd_list)
. cmds_str
' & '.join(cmd_list)
获得cmds_str
。
I don't use Windows but it works on Linux. 我不使用Windows,但可以在Linux上使用。
You can try pexpect
with cmd.exe
您可以使用
cmd.exe
尝试pexpect
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
. 它运行
cmd.exe
,在child.sendline()
发送命令,并寻找提示child.expect_exact("> ")
以获取命令child.before
生成的所有文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.