2016-09-26 24 views
0

我將命令提示符的運行時變量傳遞給python以在那裏執行(im = n python)。現在我想存儲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程序的結果返回到命令提示符

回答

1

讓我知道這是否有幫助。 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> 
-1

假設其從正在調用Python函數一個bash腳本,它應該像做:

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

local pythonReturnOutput = $(callPython) 

,你現在可以使用pythonReturnOutput。

如果您沒有使用bash,shell腳本,則此答案可能不正確。不過,我強烈建議制定一個腳本,如果它還沒有。

+0

這顯然不是一個bash腳本; OP使用Windows路徑並在標籤中顯式引用'cmd'。 –

+0

Bash腳本也可以在Windows中工作:http://www.howtogeek.com/261591/how-to-create-and-run-bash-shell-scripts-on-windows-10/ – prabodhprakash

+0

它特定於Windows 10 。那麼Windows 2008服務器和Windows 2012服務器和其他版本呢? –

0

這取決於具體情況。如果您的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 
相關問題