簡體   English   中英

Python腳本到批處理文件

[英]Python script to Batch file

我有一個運行 python 腳本的批處理文件。 我正在運行 Python 3.2。 我想將python腳本中的整數或字符串等變量發送回批處理文件,這可能嗎?

我知道我可以使用sys.argv在 Python 腳本中接受命令行參數。 希望有一些功能可以讓我做相反的事情。

在您的 Python 腳本中,只需寫入標准輸出: sys.stdout.write(...)

我不確定您使用的是哪種腳本語言,也許您可​​以詳細說明一下,現在我假設您使用的是bash (unix shell)。 因此,在您的批處理腳本中,您可以將 python 腳本的輸出轉換為這樣的變量:

#run the script and store the output into $val
val = `python your_python_script.py`
#print $val
echo $val

編輯原來是Windows批處理

python your_python_script.py > tmpFile 
set /p myvar= < tmpFile 
del tmpFile 
echo %myvar%

如果int對你來說足夠了,那么你可以使用

sys.exit(value)

在你的 python 腳本中。 退出應用程序,狀態碼為value

在您的批處理文件中,您可以將其作為%errorlevel%環境變量讀取。

你不能“發送”一個字符串。 您可以將其打印出來並讓調用進程捕獲它,但您只能直接返回 0 到 255 之間的數字。

伊格納西奧死定了。 您唯一可以返回的是退出狀態。 我之前所做的是讓 python 腳本(或在我的情況下為 EXE)輸出下一個要運行的批處理文件,然后您可以輸入您想要的任何值並運行它。 調用python腳本的批處理文件然后調用您創建的批處理文件。

您可以針對此問題嘗試使用此批處理腳本,例如:

@echo off

REM     %1 - This is the parameter we pass with the desired return code for the Python script that will be captured by the ErrorLevel env. variable.  
REM     A value of 0 is the default exit code, meaning it has all gone well. A value greater than 0 implies an error
REM     and this value can be captured and used for any error control logic and handling within the script
   
set ERRORLEVEL=
set RETURN_CODE=%1

echo (Before Python script run) ERRORLEVEL VALUE IS: [ %ERRORLEVEL% ]
echo.

call python -c "import sys; exit_code = %RETURN_CODE%; print('(Inside python script now) Setting up exit code to ' + str(exit_code)); sys.exit(exit_code)"

echo.
echo (After Python script run) ERRORLEVEL VALUE IS: [ %ERRORLEVEL% ]
echo.

當您使用不同的返回碼值運行它幾次時,您可以看到預期的行為:

PS C:\Scripts\ScriptTests> & '\TestPythonReturnCodes.cmd' 5

(Before Python script run) ERRORLEVEL VALUE IS: [ 0 ]

(Inside python script now) Setting up exit code to 5

(After Python script run) ERRORLEVEL VALUE IS: [ 5 ]

PS C:\Scripts\ScriptTests> & '\TestPythonReturnCodes.cmd' 3

(Before Python script run) ERRORLEVEL VALUE IS: [ 0 ]

(Inside python script now) Setting up exit code to 3

(After Python script run) ERRORLEVEL VALUE IS: [ 3 ]

PS C:\Scripts\ScriptTests

暫無
暫無

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

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