Python 子进程 - 在创建的新命令提示符中运行第二个命令

标签 python python-3.x subprocess

Python 3.6.7、Windows 7/10

我必须使用 subprocess.run 依次运行两个命令。第一个命令打开一个新的命令提示符。下一个命令需要在新创建的命令提示符中运行。使用下面的代码,第二个命令始终在初始命令提示符中运行。这可以吗?

import subprocess

subprocess.run('first command', shell=True)  #first command opens a new command prompt
subprocess.run('second command', shell=True)  #second command needs to be run in the newly created command prompt

最佳答案

这取决于您想要运行哪些命令,但我认为一种解决方案是创建一个批处理脚本,依次运行这两个命令。

或者您可以尝试在第一个子进程的标准输入上编写第二个命令,如下所示:

pipe = subprocess.Popen('first command', shell=True, stdin=subprocess.PIPE)
pipe.communicate(input='second command')

但我不确定这是否有效,因为该过程将在第一个命令终止后立即完成?

编辑:添加缩进

关于Python 子进程 - 在创建的新命令提示符中运行第二个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54887990/

相关文章:

python - 读取txt文件的第一行和最后一行;最快的方法和子流程故障排除

python - 两个日期之间的工作日,不包括 python 中的假期

Python:Tkinter TclError:无法调用 "image"命令

Python 3.2 类型错误 : unsupported operands(s) for %: 'NoneType' and 'str'

python - 如何使用子进程在python中解压gz文件

python - 使用 Python 子进程在 stdout 上捕获 C 程序的输出?希望吗?

python - 确保 Pandas 数据框中连续观察之间的最小时间间隔

Python调用外部软件命令

python - 我们可以将部分 css 文件包含到模板文件中吗?

python - 知道 python 脚本在由 crontab 启动时可以从 stdin 读取一些东西