Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

7zip Commands from Python

Tags:

python

7zip

There is a post on this topic already, but it does not have an explicit answer to the fundamental question which I am re-asking here:

How do you make 7zip commands from Python?

Attempting to use the subprocess module, I implemented the following which runs but does nothing (from what I can tell):

import subprocess
cmd = ['7z', 'a', '"Test.7z"', '"Test"', '-mx9']
subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)

I know that the following 7zip command works, as I have tested on the Windows command line itself:

7z a "Test.7z" "Test" -mx9

How could I implement that simple 7zip command from Python?

like image 975
nairware Avatar asked Jun 16 '12 21:06

nairware


People also ask

How do I run 7 zip from command line?

To begin a session, open a terminal window. Invoke the version of 7Zip you are using by entering "7z" for P7Zip (7z.exe), or "7za" for 7Zip for Windows (7za.exe) to start either the P7-Zip or 7za application prior to entering commands.

How do I load a 7z file in Python?

If you want to look inside a 7z archive directly within Python, then you'll need to use a library. Here's one: https://pypi.python.org/pypi/libarchive - I can't vouch for it as I said - I'm not a Python user - but using a 3rd party library is usually pretty easy in all languages. Generally, 7z Support seems limited.


2 Answers

import subprocess
cmd = ['7z', 'a', 'Test.7z', 'Test', '-mx9']
sp = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
like image 111
nairware Avatar answered Sep 20 '22 16:09

nairware


You can wrap it as a function using the following:

import subprocess

def sevenzip(filename, zipname, password):
    print("Password is: {}".format(password))
    system = subprocess.Popen(["7z", "a", zipname, filename, "-p{}".format(password)])
    return(system.communicate())

This definitely works as I've tried and tested it. If you want to tweak it i.e. to Extract files then you can use the following:

def extractfiles(zipname):
    system = subprocess.Popen(["7z", "e", zipname])
    return(system.communicate())

Give this a try and lemme know how you get on.

Bear in mind this is for Linux. In Windows, swap "7z" with "C:\Program Files\7-Zip\7z.exe" (i think that's the right location).

like image 39
Naufal Avatar answered Sep 18 '22 16:09

Naufal