简体   繁体   English

如果从 python 脚本执行或双击执行,为什么批处理文件不起作用?

[英]Why batch file is not working if executed from python script or if executed by double clicking it?

I have a batch script which is generating a configuration file after its execution, the configuration file generated has some data inside it.我有一个批处理脚本,它在执行后生成一个配置文件,生成的配置文件里面有一些数据。 When i execute it from command prompt as follows i get the desired output :当我按如下方式从命令提示符执行它时,我得到了所需的输出:

C:/> start.bat

but if i try to execute from python script as follows or even if i double click and execute it i do get the configuration file but it does not contain any required data it just have '0' inside it:但是如果我尝试从 python 脚本执行如下,或者即使我双击并执行它,我确实得到了配置文件,但它不包含任何必需的数据,它里面只有“0”:

import subprocess as sp
p= sp.Popen("C:/pathtobatch/start.bat",stdin=sp.PIPE, stdout = sp.PIPE, stderr=sp.PIPE)

Inside the batch script(start.bat) i am actually executing a python script and retrieving its data to a configuration file as follows:在批处理脚本(start.bat)中,我实际上正在执行一个 python 脚本并将其数据检索到一个配置文件中,如下所示:

python C:\inetpub\ftproot\sample.py > log.txt
set  myvar =< log.txt
del log.txt
echo %errorlevel% %myvar% >C:\inetpub\ftproot\config.txt

I need to execute the batch(start.bat) from the python script and generate the config.txt file having the required data.我需要从 python 脚本执行批处理(start.bat)并生成具有所需数据的 config.txt 文件。 So, how shall i do that.那么,我该怎么做。 Why the start.bat is not working fine if i double click it and why is it working fine if i am executing it from command prompt.如果我双击它,为什么 start.bat 不能正常工作,如果我从命令提示符执行它,为什么它可以正常工作。

Is it possible that you get '0' as it is the value of %errorlevel%?是否有可能得到 '0',因为它是 %errorlevel% 的值?

I found two issues in your case:我在你的案例中发现了两个问题:

1) batch file - can you please update your batch file to something like: 1)批处理文件 - 您能否将批处理文件更新为:

for /f %%i in ('python C:\inetpub\ftproot\sample.py') do set myvar=%%i
echo %errorlevel% %myvar% >C:\inetpub\ftproot\config.txt

Credit for the idea of setting variable: https://stackoverflow.com/a/2340018/5088142归功于设置变量的想法: https : //stackoverflow.com/a/2340018/5088142

2) python script - can you please update your python script to be: 2)python 脚本 - 您能否将您的 python 脚本更新为:

import os
os.system("C:/pathtobatch/start.bat")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM