猿问

如何使用 Path 对象 + 字符串构建 os.system() 命令?

我正在尝试编写一个脚本,该脚本从配置文件中提取一些路径并调用系统 shell 以使用该路径作为命令的一部分来运行命令。它基本上是一个解压缩目录中所有文件的摘要脚本。请记住,我正在自学 Python,这是我的第一个 Python 脚本,也是我的第一篇文章。请原谅我在礼仪方面的任何错误。


目标是让命令“C:\Program Files\WinRAR\Rar.exe x”在目录上运行。不幸的是,我了解到 Python 不允许您将字符串连接到 Path 对象,大概是因为它们是两种不同的元素类型。我有以下内容:


在配置文件中:


[Paths]

WinrarInstallPath = C:\Program Files\WinRAR\

NewFilesDirectory = M:\Directory\Where\Rar Files\Are\Located

脚本:


**SOME CODE***

new_files_dir = Path(config.get('Paths', 'NewFilesDirectory'))

winrar_dir = Path(config.get('Paths', 'WinrarInstallPath'))


**SOME MORE CODE**

os.chdir(new_files_dir)

for currentdir, dirnames, filenames in os.walk('.'):

    os.system(winrar_dir + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')

这给了我错误“TypeError:+的不支持的操作数类型:'WindowsPath'和'str'”


我试过了


os.system(str(winrar_dir) + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')

但它不处理目录名称中的空格。我也试过


os.system(os.path.join(winrar_dir, "rar.exe x ") + os.getcwd() + currentdir[1:] + '\\*.rar')

结果相同


我意识到我可以从一开始就将它视为一个字符串并执行以下操作


wrd = config.get('Paths', 'WinrarInstallationPath')

winrar_dir = '"' + wrd + '"'


os.system(winrar_dir + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')

但是到目前为止,Python 一直很流畅,而且感觉很笨拙,所以我觉得我错过了一些东西,但到目前为止我还没有找到答案。


一只甜甜圈
浏览 161回答 2
2回答

萧十郎

不要使用os.system. 使用subprocess.call:os.system(winrar_dir + "rar.exe x " + os.getcwd() + currentdir[1:] + '\\*.rar')该列表实际上就是 argv 数组。无需为外壳报价。subprocess.call([os.path.join(winrar_dir, 'rar.exe'), 'x', os.getcwd(), os.path.join(currentdir[1:], '*.rar')])您可能还会看到我不喜欢 pathlib 模块。我使用了它的前身路径,只发现它的 walkfiles 方法有用。

Cats萌萌

如果您要尝试添加到一个pathlib.Path对象,您需要添加它的joinpath方法以添加到路径中,而不是+像您将用于字符串一样的运算符(这就是给您的TypeError)。# From the docs:Path('c:').joinpath('/Program Files')Out[]: PureWindowsPath('c:/Program Files')如果您仍然遇到问题,请使用Path.exists()方法或Path.glob方法测试您正在读取的路径是否指向正确的位置。
随时随地看视频慕课网APP

相关分类

Python
我要回答