How to run bash commands using subprocess.run on windows(如何使用子进程运行bash命令。在Windows上运行)
本文介绍了如何使用子进程运行bash命令。在Windows上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在python3.7.4中使用subprocess.run()运行外壳脚本和git-bash命令。当我在subprocess documentation page上运行该简单示例时,会发生以下情况:
import subprocess
subprocess.run(["ls", "-l"])
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:pycharmprojectenvslibsubprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:pycharmprojectenvslibsubprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:pycharmprojectenvslibsubprocess.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环境。我还安装了git-bash。
我也尝试设置环境,但得到相同的错误。
import os
import subprocess
my_env = os.environ.copy()
my_env["PATH"] = 'C:Program FilesGit;' + 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:pycharmprojectenvslibsubprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:pycharmprojectenvslibsubprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:npycharmprojectenvslibsubprocess.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 FilesGitgit-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中所示,如能以最佳方式使其正常工作,我将不胜感激。
推荐答案
我发现可以使用...Gitinash.exe而不是...Gitgit-bash.exe运行命令,如下所示:
import subprocess
subprocess.run(['C:Program FilesGit\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
__pycache__
conda_create.sh
envs
main.py
test.sh
zipped
')
这篇关于如何使用子进程运行bash命令。在Windows上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何使用子进程运行bash命令。在Windows上运行
基础教程推荐
猜你喜欢
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
