简体   繁体   中英

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:

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:

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. 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.

Is it possible that you get '0' as it is the value of %errorlevel%?

I found two issues in your case:

1) batch file - can you please update your batch file to something like:

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

2) python script - can you please update your python script to be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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