如何在 windows 上使用 subprocess.run 运行 bash 命令

How to run bash commands using subprocess.run on windows

我想 运行 shell 脚本和 git-bash 命令使用 subprocess.run(),在 python 3.7.4 中。当我 运行 subprocess documentation page 上的简单示例时,会发生这种情况:

import subprocess

subprocess.run(["ls", "-l"])

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\pycharm\project\envs\lib\subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\pycharm\project\envs\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\pycharm\project\envs\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified


# it also fails with shell=True
subprocess.call(["ls", "-l"], shell=True)

'ls' is not recognized as an internal or external command,
operable program or batch file.
1

来自 shell=True 的消息是来自 windows cmd 的消息,这表明子进程未向 git-bash 发送命令。

我正在为 python 使用位于 project/envs/ 文件夹中的 conda 环境。我还安装了 git-bash.

我也尝试设置 env 并得到同样的错误。

import os
import subprocess

my_env = os.environ.copy()
my_env["PATH"] = 'C:\Program Files\Git\;' + my_env["PATH"]
subprocess.run(['git-bash.exe', 'ls', '-l'], env=my_env)

Traceback (most recent call last):
  File "<input>", line 3, in <module>
  File "C:\pycharm\project\envs\lib\subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\pycharm\project\envs\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:n\pycharm\project\envs\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

我可以通过指向 git-bash.exe 将它转到 运行,但它 returns 是一个空字符串而不是我目录中的文件

import subprocess
subprocess.run(['C:\Program Files\Git\git-bash.exe', 'ls', '-l'], capture_output=True)

CompletedProcess(args=['C:\Program Files\Git\git-bash.exe', 'ls', '-l'], returncode=0, stdout=b'', stderr=b'')


我将不胜感激任何有关实现此功能的最佳方法的建议,如 subprocess documentation page 所示。

试试这个

p = subprocess.Popen(("ls", "-l"), stdout=subprocess.PIPE)
nodes = subprocess.check_output(("grep"), stdin=p.stdout)
p.wait()
  • ls 是 Linux shell 列出文件和目录的命令
  • dir 是 Windows 用于列出文件和目录的命令行命令

尝试在Windows命令行中运行dir。如果有效,请尝试使用 python 子进程 运行 相同的命令:

import subprocess

subprocess.run(["dir"])

我发现我可以 运行 命令使用 ...Git\bin\bash.exe 而不是 ...\Git\git-bash.exe,像这样:

import subprocess
subprocess.run(['C:\Program Files\Git\bin\bash.exe', '-c','ls'], stdout=subprocess.PIPE)

CompletedProcess(args=['C:\Program Files\Git\bin\bash.exe', '-c', 'ls'], returncode=0, stdout=b'README.md\n__pycache__\nconda_create.sh\nenvs\nmain.py\ntest.sh\nzipped\n')

For a machine with Windows Operating System, Try the following

import subprocess
subprocess.run(["dir", "/p"], shell=True)

“ls”替换为“dir”,“-l”替换为“/l”,“shell”设置为 true

For a machine with Linux/Mac Operating System, Try the following

import subprocess
subprocess.run(["ls", "-l"])