how to execute 7zip commands from python script

不问归期 提交于 2019-12-10 19:37:12

问题


I am trying to get a basic idea of how the os.system module can be used to execute 7zip commands. For now I don't want to complicate things with Popen or subprocess. I have installed 7zip and copied the 7zip.exe into my users folder. I just want to extract my test file install.zip. However using the code below causes the shell to appear briefly before exiting and no unzip has occurred. Please could you tell me why?

def main():
    try:

         os.system(r"C:\Users\Oulton\ 7z e C:\Users\Oulton\install.zip")
    except:
            time.sleep(3)
            traceback.print_exc

if __name__ == "__main__":
    main()

Many Thanks


回答1:


There are several problems with the following line:

os.system("C:\Users\Oulton\ 7z e C:\Users\Oulton\install.zip  ")

Since your string contains backslashes, you should use a raw string:

os.system(r"C:\Users\Oulton\7z -e C:\Users\Oulton\install.zip")

(note the r before the first double quote.)

I've also removed the extraneous spaces. The first one (before the 7z) was definitely problematic.

Also note that the traceback.print_exc does not call the function. You need to add parentheses: traceback.print_exc().

Finally, it is recommended that in new code the subprocess module is used in preference to os.system().




回答2:


Can be done using sub process module:

import subprocess

beforezip = D:\kr\file                         #full location
afterzip = filename.zip
Unzipped_file = "7z a \"%s\" \"%s\"" %( afterzip, beforezip )
retV = subprocess.Popen(cmdExtractISO, shell=True, stdout=subprocess.PIPE, 
stderr=subprocess.STDOUT)
outData = retV.stdout.readlines();


来源:https://stackoverflow.com/questions/9128169/how-to-execute-7zip-commands-from-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!