python - 如何在 Windows 上使用 subprocess.run 运行 bash 命令

标签 python python-3.x subprocess python-3.7

我想使用 subprocess.run() 运行 shell 脚本和 git-bash 命令,在 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 发送命令。

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

我也尝试设置环境并得到相同的错误。

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 来运行它,但它返回一个空字符串而不是我目录中的文件

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 所示,我将不胜感激有关使其正常工作的最佳方法的任何建议。 .

最佳答案

我发现我可以使用 ...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')

关于python - 如何在 Windows 上使用 subprocess.run 运行 bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58402900/

相关文章:

python - 在python断言中,断言失败时如何打印条件?

python - 如何编写subprocess.Popen终端执行

python - 如何从子进程中获取环境?

python - Snakemake - 从输入文件动态派生目标

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

python - python 的 selenium 的导入错误

Python 字符串格式化

python heapq排序列表错误?

python - 区分类型别名和实际类的约定?

python - 将 bytearray 转换为 array.array ('B' )