python - 如何使用 Python 的子进程模块在终端中执行两个命令?

标签 python linux subprocess popen

如何使用子进程模块(即 callcheck_callPopen)运行多个命令?

例如,假设我想快速连续执行两次 ls 命令,以下语法不起作用

import subprocess
subprocess.check_call(['ls', 'ls'])

返回:

CalledProcessError: Command '['ls', 'ls']' returned non-zero exit status 2.

最佳答案

您可以使用&&;:

$ ls && ls
file.txt file2.txt
file.txt file2.txt

$ ls; ls
file.txt file2.txt
file.txt file2.txt

不同之处在于,在 && 的情况下,第二个命令只有在第一个命令成功时才会执行(尝试 false && ls),这与 不同; 在这种情况下,命令将独立于第一次执行执行。

因此,Python 代码将是:

import subprocess
subprocess.run(["ls; ls"], shell=True)

关于python - 如何使用 Python 的子进程模块在终端中执行两个命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632829/

相关文章:

python - 问题在 Python 中运行程序 (R) 以执行操作(执行脚本)

python - 将递归字符串搜索重构为二分搜索,达到最大递归深度

linux - tiny6410 friendlyarm 连接到电容式 lcd 但触摸在 linux 中不起作用

Python子进程模块使用

linux - 使 awk 打印单行的特定段

c - 如何检查内存区域是否映射到文件?

python 3.4子进程

两个时间序列的python聚合

python - `cimport` 导致交互式 Python 解释器出错

python - multiprocessing.Pool 在关闭/加入后无限期挂起