如何在同一 shell 中使用 python 在 cmd 中执行多个 windows 命令
How to perform multiple windows command in cmd using python in same shell
我想一个接一个地执行一些命令并存储到相同的变量中 shell。每当我尝试执行下一个命令时,它都会在新 shell
中执行
import subprocess
cmd1 = 'cd C:\Program Files (x86)\openvpn\bin\'
output = subprocess.getoutput(cmd1) # it goes to the above directory
cmd2 = 'openvpn.exe --help'
output2 = subprocess.getoutput(cmd2)
在 cmd2 运行时,一个新的 shell 执行此命令并告诉--
'openvpn.exe' 未被识别为内部或外部命令,
可运行的程序或批处理文件。
我想一个接一个地执行几个命令并存储到变量中。所以我可以在其他命令中使用该变量。
您应该使用 run
方法,如下所示:
output = subprocess.run(['openvpn.exe', '--help'], cwd='C:\Program Files (x86)\openvpn\bin\', capture_output=True)
- cwd = current working directory (where should the command run)
- capture_output = record the stdout, stderr streams
然后您可以在 stdout、stderr 属性中访问您的结果:
output.stdout # will give you back the output of the command.
您没有得到任何结果,因为 cd
命令在 subprocess
中无效。它首先与 cd
的工作方式有关——没有进程可以更改另一个进程的工作目录。
我想一个接一个地执行一些命令并存储到相同的变量中 shell。每当我尝试执行下一个命令时,它都会在新 shell
中执行import subprocess
cmd1 = 'cd C:\Program Files (x86)\openvpn\bin\'
output = subprocess.getoutput(cmd1) # it goes to the above directory
cmd2 = 'openvpn.exe --help'
output2 = subprocess.getoutput(cmd2)
在 cmd2 运行时,一个新的 shell 执行此命令并告诉-- 'openvpn.exe' 未被识别为内部或外部命令, 可运行的程序或批处理文件。
我想一个接一个地执行几个命令并存储到变量中。所以我可以在其他命令中使用该变量。
您应该使用 run
方法,如下所示:
output = subprocess.run(['openvpn.exe', '--help'], cwd='C:\Program Files (x86)\openvpn\bin\', capture_output=True)
- cwd = current working directory (where should the command run)
- capture_output = record the stdout, stderr streams
然后您可以在 stdout、stderr 属性中访问您的结果:
output.stdout # will give you back the output of the command.
您没有得到任何结果,因为 cd
命令在 subprocess
中无效。它首先与 cd
的工作方式有关——没有进程可以更改另一个进程的工作目录。