繁体   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