处理带空格的目录 Python subprocess.call()

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

我正在尝试创建一个程序来扫描文本文件并将参数传递给子进程。一切正常,直到我得到路径中带有空格的目录。

我的 split 方法,它分解了参数在空格上的绊脚石:

s = "svn move folder/hello\ world anotherfolder/hello\ world"

task = s.split(" ")
process = subprocess.check_call(task, shell = False)

做,要么我需要函数来解析正确的参数,要么我将整个字符串传递给子进程而不先分解它。

不过我有点失落。

python subprocess directory
2个回答
23
投票

使用列表代替:

task = ["svn",  "move",  "folder/hello world", "anotherfolder/hello world"]
subprocess.check_call(task)

如果您的文件包含整个命令,而不仅仅是路径,那么您可以尝试 shlex.split():

task = shlex.split(s)
subprocess.check_call(task)

0
投票

这对我尝试从不规则文件夹结构中的音乐目录获取非常复杂的文件规格到ffplay有很大帮助。我从来没有让它在 os.system() 调用中或在 subprocess.call() 中使用字符串变量。它只能将字符串直接放入调用中。

subprocess.call( "ffplay", "-nodisp", "-autoexit", 'complex path string' )

我终于找到了jfs建议的列表方法(谢谢!)。它允许使用文件规范的变量。关键是将变量放入表中,字符串中不嵌入任何引号。该列表提供了所需的报价并且效果很好!这是“列表”解决方案:

songspec = "a complex /media/mint filespec without embedded quotes!"
playsong = ["ffplay", "-nodisp", "-autoexit", songspec]

这非常有效,我可以毫无问题地自动浏览我的歌曲列表。我花了大约 3 个小时才使这一操作正常运行。

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