簡體   English   中英

如何在命令提示符下存儲python程序的輸出?

[英]How to store output of a python program in command prompt?

我正在將運行時變量從命令提示符傳遞到python,以便在那里執行(im = n python)。 現在,我想存儲python程序的結果,並將這些結果重新用於命令提示符。 示例如下

set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_publish\projection_raster.py %input%

我將用戶輸入字符串從命令提示符傳遞給python程序,如上所述。 如何使用python程序的結果返回到命令提示符

讓我知道是否有幫助。

python文件(c.py)的代碼:

import sys

print('You passed ',sys.argv[1])

Windows批處理代碼(a.bat):

@echo off

set input=

set /P input=Enter Layer Name:%=%

(python c.py %input%) > tmp.txt

set /P output=<tmp.txt

echo %output%

批處理代碼輸出:

C:\Users\dinesh_pundkar\Desktop>a.bat
Enter Layer Name:Dinesh
You passed  Dinesh
C:\Users\dinesh_pundkar\Desktop>

這要視情況而定。 如果您的Python代碼正在退出一個值(帶有exit(<returncode>) ),則可以從%ERRORLEVEL%環境變量中檢索它。

<yourpythoncommand>
echo Return code: %ERRORLEVEL%

如果您願意捕獲和處理標准輸出,則需要使用FOR循環:

FOR /F "delims=" %%I IN ('<yourpythoncall>') DO CALL :processit %%I
GOTO :EOF

:processit
echo Do something with %1
GOTO :EOF

現在,如果您不想逐行處理輸出,最簡單的方法就是將輸出重定向到一個臨時文件。

<yourpythoncommand> >%TEMP%\mytempfile.txt
<do something with %TEMP%\mytempfile.txt>
del %TEMP%\mytempfile.txt

假設它是從您調用python函數的位置開始的bash腳本,則應按照以下步驟操作:

function callPython()
{
    local pythonResult=<code for calling python>
    echo $pythonResult
}

local pythonReturnOutput = $(callPython)

現在您可以使用pythonReturnOutput了。

如果您未使用bash shell腳本,則此答案可能是錯誤的。 但是,如果沒有腳本,我強烈建議您使用它。

暫無
暫無

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

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