[英]Run bash script from Python but get Windows Error 193
我嘗試從 Python 運行 shell 腳本,但我得到了
WindowsError: [Error 193] %1 is not a valid Win32 application
我的簡化代碼如下:
import subprocess
subprocess.call(["%s/scripts/test.sh"%work_path, "arg1", "arg2"])
奇怪的是,這在 Linux 上運行順暢。
test.sh
在頭文件中有 bash 的有效路徑,bash 可執行文件包含在%PATH%
。 我什至嘗試使用參數shell=True
,但結果是一樣的。
我有同樣的問題。 這是我在 MinGW (msysgit) 中從 python 運行 shell 腳本的方式:
from subprocess import call
arg1 = 1
arg2 = 10
cmd = ['C:\\Program Files (x86)\\Git\\bin\\bash.exe', '-c', '~/bin/myscript', arg1, arg2]
result_code = call(cmd)
關鍵是明確說明 bash.exe 的路徑作為第一個參數,'-c'(命令)作為第二個參數,並使用腳本作為第三個參數。 隨后的參數進入腳本(有時——見下文)。
一些注意事項:
%PROGRAMFILES%
和其他 Windows 變量在搜索 bash.exe 文件時無法解析 - 您可能可以通過使用 python 構建路徑而不是硬編碼名稱來解決這個問題。
將 ~ 替換為您的 mingw 主目錄有效,並且.bashrc
或.profile
的 PATH 變量有效。 如果省略“-c”參數,則可以訪問本地腳本(在 ~ 中),但是“true”和“ls”等命令不存在 mingw 根文件結構。
例如,我還沒有弄清楚何時組合參數以及何時不組合它們,此命令有效:
cmd = ['C:\\\\Program Files (x86)\\\\Git\\\\bin\\\\bash.exe', '-c', 'echo hi'] result_code = call(cmd)
但這不是:
cmd = ['C:\\\\Program Files (x86)\\\\Git\\\\bin\\\\bash.exe', '-c', 'echo', 'hi'] result_code = call(cmd)
但是,使用我的 shell 腳本,這是有效的:
cmd = ['C:\\\\Program Files (x86)\\\\Git\\\\bin\\\\bash.exe', '-c', '~bin/myscript', arg1, arg2] result_code = call(cmd)
但這不是:
cmd = ['C:\\\\Program Files (x86)\\\\Git\\\\bin\\\\bash.exe', '-c', '~bin/myscript 1 10'] result_code = call(cmd)
在所有情況下 result_code 為 0 表示成功執行 bash.exe。 我不知道如何將腳本的輸出返回給 python。 這會打印輸出但不會將其發送回主進程。 我需要將結果返回給調用程序,但這可能是另一個涉及輸出管道和文件重定向的問題。
簡而言之。 這完全是一團糟,但腳本可以執行。 當然,某處有更一致的技術。
以下對我來說效果很好:
import platform, os, subprocess
if platform.system() == 'Windows':
programfiles = ('PROGRAMW6432' if platform.architecture()[0] == '32bit'
else 'PROGRAMFILES')
bash_exe = os.getenv(programfiles) + r'\Git\bin\bash'
subprocess.call([bash_exe, '-c', 'echo hello'])
如果bash.exe
路徑中有空格,則無法使用子bash.exe
調用 bash。 解決此問題的捷徑是在Path環境變量中添加bash.exe
。 之后,您可以按如下方式執行 bash 腳本。
import subprocess
command = ['bash.exe', shell_script]
return_code = subprocess.call(command)
print('return code:' + str(return_code))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.