簡體   English   中英

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

[英]How to run bash commands using subprocess.run on windows

我想在 python 3.7.4 中使用 subprocess.run subprocess.run()運行 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

來自shell=True的消息是來自 windows cmd 的消息,這表明子進程沒有向 git-bash 發送命令。

我正在為 python 使用位於project/envs/文件夾中的 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'')


子流程文檔頁面所示,我將不勝感激有關使其正常工作的最佳方法的任何建議。

嘗試這個

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"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM