如何从python脚本执行7zip命令 [英] how to execute 7zip commands from python script

查看:47
本文介绍了如何从python脚本执行7zip命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用 os.system 模块来执行 7zip 命令.现在我不想用 Popen 或子进程使事情复杂化.我已经安装了 7zip 并将 7zip.exe 复制到我的用户文件夹中.我只想解压缩我的测试文件 install.zip.但是,使用下面的代码会导致 shell 在退出之前短暂出现并且没有解压缩.请你告诉我为什么?

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:UsersOulton 7z e C:UsersOultoninstall.zip")
    except:
            time.sleep(3)
            traceback.print_exc

if __name__ == "__main__":
    main()

非常感谢

推荐答案

下面一行有几个问题:

os.system("C:UsersOulton 7z e C:UsersOultoninstall.zip  ")

由于您的字符串包含反斜杠,您应该使用 原始字符串:

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

os.system(r"C:UsersOulton7z -e C:UsersOultoninstall.zip")

(注意第一个双引号之前的 r.)

(note the r before the first double quote.)

我还删除了多余的空格.第一个(在 7z 之前)肯定有问题.

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

另请注意,traceback.print_exc 不会调用该函数.需要加括号:traceback.print_exc().

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

最后,建议在新代码中subprocess 模块 优先使用 os.system().

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

这篇关于如何从python脚本执行7zip命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆