Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a specific war file to a specific folder

Tags:

python

jar

I have the python code which will download the .war file and put it in a path which is specified by the variable path.

Now I wish to extract a specific file from that war to a specific folder.

But I got struck up here :

os.system(jar -xvf /*how to give the path varible here*/  js/pay.js)

I'm not sure how to pass on the variable path to os.system command.

I'm very new to python, kindly help me out.

like image 368
sriram Avatar asked Jan 21 '26 11:01

sriram


1 Answers

If you really want to use os.system, the shell command line is passed as a string, and you can pass any string you want. So:

os.system('jar -xvf "' + pathvariable + '" js/pay.js)

Or you can use {} or %s formatting, etc.

However, you probably do not want to use os.system.

First, if you want to run other programs, it's almost always better to use the subprocess module. For example:

subprocess.check_call(['jar', '-xvf', pathvariable, 'js/pay.js'])

As you can see, you can pass a list of arguments instead of trying to work out how to put a string together (and deal with escaping and quoting and all that mess). And there are lots of other advantages, mostly described in the documentation itself.

However, you probably don't want to run the war tool at all. As jimhark says, a WAR file is just a special kind of JAR file, which is just a special kind of ZIP file. For creating them, you generally want to use JAR/WAR-specific tools (you need to verify the layout, make sure the manifest is the first entry in the ZIP directory, take care of the package signature, etc.), but for expanding them, any ZIP tool will work. And Python has ZIP support built in. What you want to do is probably as simple as this:

import zipfile
with zipfile.ZipFile(pathvariable, 'r') as zf:
    zf.extract('js/pay.js', destinationpathvariable)

IIRC, you can only directly use ZipFile in a with statement in 2.7 and 3.2+, so if you're on, say, 2.6 or 3.1, you have to do it indirectly:

from contextlib import closing
import zipfile
with closing(zipfile.ZipFile(pathvariable, 'r')) as zf:
    zf.extract('js/pay.js', destinationpathvariable)

Or, if this is just a quick&dirty script that quits as soon as it's done, you can get away with:

import zipfile
zf = zipfile.ZipFile(pathvariable, 'r')
zf.extract('js/pay.js', destinationpathvariable)

But I try to always use with statements whenever possible, because it's a good habit to have.

like image 139
abarnert Avatar answered Jan 23 '26 01:01

abarnert