![](/img/trans.png)
[英]Can we execute multiple commands in the same command prompt launched by python
[英]Execute multiple shell/command prompt commands in same instance
我正在尋找一種在同一個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()
如果您想知道為什么必須將其分開,則要運行的命令來自用戶輸入。 是的,我意識到這是一種安全風險,但是在這種情況下,安全性不是問題,因為它純粹是一種教育冒險,不會被用於任何用途
您可以將subprocess.check_call(cmds_str, shell=True)
與同一行中的多個命令結合使用: 如何在Windows CMD中的一行中運行兩個命令?
您可以分別構建每個命令並將它們添加到列表中,然后使用' & '.join(cmd_list)
. cmds_str
' & '.join(cmd_list)
獲得cmds_str
。
我不使用Windows,但可以在Linux上使用。
您可以使用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)
它運行cmd.exe
,在child.sendline()
發送命令,並尋找提示child.expect_exact("> ")
以獲取命令child.before
生成的所有文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.