如何使用 subprocess.call 执行包含空格的文件名命令?
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《如何使用 subprocess.call 执行包含空格的文件名命令?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。
如何使用 subprocess.call 执行 linux 命令,即使文件名中有空格
在 linux 环境中,可以使用 cat 命令将具有空格的文件名合并。例如,以下命令将 1 1.txt 和 1 2.txt 合并到 1 3.txt 中:
cat './temp/1 1.txt' './temp/1 2.txt' > './temp/1 3.txt'
使用 python 中的 subprocess.call 模块可以执行 linux 命令。但是,当文件名中有空格时,需要进行特殊处理。
问题代码
你提供的代码如下:
import subprocess cmdu = 'cat●"./temp/1 1.txt"●"./temp/1 2.txt"●>●"./temp/1 3.txt"' subprocess.call(cmdu.split('●'))
此代码将命令拆分为以下部分:
['cat', '"./temp/1 1.txt"', '"./temp/1 2.txt"', '>', '"./temp/1 3.txt"']
但是,因为”>” 符号也被拆分,因此该命令将无法正确执行。
解决方案
要解决此问题,可以使用 subprocess.call 的 shell 参数。此参数指定是否应使用 shell 来执行命令。在使用 shell(shell=true)时,可以使用管道符号(|)将命令连接起来。
以下 python 代码将正确执行该命令:
import subprocess cmdU = ['cat', './TEMP/1 1.txt', './TEMP/1 2.txt', '>', './TEMP/1 3.txt'] subprocess.call(cmdU, shell=True)
终于介绍完啦!小伙伴们,这篇关于《如何使用 subprocess.call 执行包含空格的文件名命令?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~公众号也会发布文章相关知识,快来关注吧!