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

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

问题描述

我正在尝试基本了解如何使用os.system模块执行7zip命令。目前,我不想使Popen或子流程复杂化。我已经安装了7zip,并将7zip.exe复制到我的用户文件夹中。我只想提取我的测试文件install.zip。但是,使用下面的代码会导致外壳在退出之前短暂出现,并且未发生解压缩。

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()

非常感谢

推荐答案

以下行存在一些问题:

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")

(请注意在第一个双引号之前的 r 。)

(note the r before the first double quote.)

我也删除了e无关的空间。第一个(在 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().

最后,建议在新代码中 子过程 模块是优先于 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天全站免登陆