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

问题描述 投票:0回答:2

我正在尝试编写一个脚本,该脚本从配置文件中提取一些路径,并调用系统外壳程序以将该路径作为命令的一部分来运行命令。基本上,这是一个摘要脚本,可解压缩目录中的所有文件。请记住,我正在自学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一直很流畅,而且感觉非常笨拙,所以我觉得我缺少了一些东西,但是到目前为止,我还没有找到答案。

python concatenation os.system
2个回答
0
投票

请勿使用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方法有用。


0
投票

[如果要尝试添加到pathlib.Path对象,则需要添加其joinpath方法以添加到路径,而不是像字符串那样使用+运算符(这就是给您的东西) TypeError)。

# From the docs:
Path('c:').joinpath('/Program Files')
Out[]: PureWindowsPath('c:/Program Files')

如果仍然无法通过使用Path.exists()方法或Path.glob方法来测试正在读取的路径是否指向正确的位置,

© www.soinside.com 2019 - 2024. All rights reserved.