python - 如何在 Windows 上使用 subprocess.run 运行 bash 命令
问题描述
我想subprocess.run()
在 python 3.7.4 中使用 , 运行 shell 脚本和 git-bash 命令。当我在子流程文档页面上运行简单示例时,会发生这种情况:
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
来自 windows cmd 的消息shell=True
,这表明子进程没有向 git-bash 发送命令。
我正在使用位于project/envs/
python 文件夹中的 conda 环境。我还安装了 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'')
如子流程文档页面所示,我将不胜感激有关使其正常工作的最佳方法的任何建议。
解决方案
我发现我可以使用...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')
推荐阅读
- mysql - 如何用 C 代码连接 SQL TABLE 列
- jdbc - 如何使用主题正则表达式选项创建具有多个主题的 JDBC 接收器连接器
- ldap - 当我想在我的目录中插入数据时,出现以下错误
- sql - 将 2019/05/21 00:00:00 格式转换为 21-JUN-19(即 DD-MON-YY)的 SQL 查询
- php - Guzzle POST 给我“不支持 HTTP 方法 'GET'”
- javascript - WooCommerce 产品捆绑 ajax 添加到购物车
- java - 服务停止时如何删除通知?
- android - 带有 RecyclerView 的 Activity 中的浮动操作按钮未收到 onClick
- c# - 如何在尝试使用 BotFramework 显示聊天记录时修复错误请求?
- jsf - primefaces tristatecheckbox 标签左侧