简体   繁体   中英

Get CLASSPATH constructed in a .bat file from python

The java project I am working on has a .bat file and a .sh file which build the CLASSPATH for the project to run. ( .bat for windows and .sh for the rest).

Now, I am writing a python script that needs access to the classpath created by these scripts, the one from .sh if on linux and the one from .bat if on windows.

Currently, I am doing this for linux:

Popen(['bash', '-c', '. mkcp.sh && echo $CLASSPATH'], stdout=sp.PIPE).communicate()[0].strip()

And I can't figure out an equivalent way to do this on windows. So far I've come up with this

check_output(['cmd', '/c', 'call mkcp.bat && echo %CLASSPATH%'])

But that puts all the commands in the mkcp.bat file into the stdout. (Adding @echo off to that file is not an option for me, ie, I can't modify it). That problem aside, the main problem is that the %CLASSPATH% is substituted with its value before the batch file is run, which is not what I want.

Another approach I thought of was if I create a Popen object as above and run the batch file and if I can access the environment of that process, I can get what I want. But from Popen's documentation, this doesn't look to be possible.

Any ideas on how to achieve this?

The simplest way would be to create a batch file with the relevant commands. That way the variable doesn't get expanded until CMD processes the relevant line. Also use @echo off to disable echo:

@echo off
call mkcp.bat
echo %CLASSPATH%

Then just call that batch file from your Python code.

If you want to do it without an intervening batch file try:

check_output(['cmd', '/V:ON', '/c', '"@echo off && call mkcp.bat && echo !CLASSPATH!"'])

/V:ON enables delayed expansion of environment variables when you use ! for the substitution instead of % .

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