Python脚本到批处理文件

时间:2012-05-30 17:31:11

标签: python windows batch-file

我有一个运行python脚本的批处理文件。我正在运行Python 3.2。我想从python脚本中将变量(如整数或字符串)发送回批处理文件,这可能吗?

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

5 个答案:

答案 0 :(得分:12)

在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%

答案 1 :(得分:3)

你不能“发送”一个字符串。您可以将其打印出来并让调用进程捕获它,但您只能直接返回0到255之间的数字。

答案 2 :(得分:3)

如果int足够你,那么你可以使用

sys.exit(value)
你的python脚本中的

。这将退出应用程序,状态代码为value

在批处理文件中,您可以将其作为%errorlevel%环境变量读取。

答案 3 :(得分:1)

伊格纳西奥已经死了。您唯一可以返回的是您的退出状态。我之前做的是让python脚本(或者我的情况下是EXE)输出要运行的下一个批处理文件,然后你可以放入你想要的任何值并运行它。调用python脚本的批处理文件然后调用您创建的批处理文件。

答案 4 :(得分:0)

您可以尝试使用此批处理脚本解决此问题,例如:

@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
相关问题