Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python3中获得glob表达式的反斜杠转义版本_Python_Escaping_Glob_Pathname - Fatal编程技术网

如何在python3中获得glob表达式的反斜杠转义版本

如何在python3中获得glob表达式的反斜杠转义版本,python,escaping,glob,pathname,Python,Escaping,Glob,Pathname,我正在用Python构建命令,包括一个也包含空格字符的glob表达式 我了解到建议的方法是使用shlex.quote,但它只适用于实际解析的路径名,因为将表达式封装在“或”中也会阻止shell全局扩展 最简单的例子: 我知道我可以使用任何替换技术将该字符串中的空格'替换为'\'(例如regexps),但我认为如果已经存在合适的函数,我应该首先查找它,而不是编写自己的代码 真实情况 我正在编写的命令应该会影响路径名类似的多个文件(请考虑用下划线分隔): 我想获得如下命令: rename "

我正在用Python构建命令,包括一个也包含空格字符的glob表达式

我了解到建议的方法是使用shlex.quote,但它只适用于实际解析的路径名,因为将表达式封装在
中也会阻止shell全局扩展

最简单的例子: 我知道我可以使用任何替换技术将该字符串中的空格
'
替换为
'\'
(例如regexps),但我认为如果已经存在合适的函数,我应该首先查找它,而不是编写自己的代码

真实情况 我正在编写的命令应该会影响路径名类似的多个文件(请考虑用下划线分隔):

我想获得如下命令:

rename "s/^WrongID_/RightId_/" dir/WrongID_Another\ ID\ With\ Spaces_*.*
…其中,
dir
错误ID
另一个带有空格的ID
右ID
,都是从表中读取的


许多这样的命令都被写入一个文件中,然后我将把这个脚本提供给bash。

您可能正在寻找它吗

while read -p dir wrong rest right; do
    rename "s/^${wrong}_/${right}_/" "$dir/${wrong}_${rest}_"*.*
done <<\____
    one    few     other   many
    two    theyre  stuff   there
    three  grammer correct grammar
____

使用Python运行Bash命令来驱动Perl工具,我们是不是…?Bash已经为这个用例提供了
printf“%q”
,不过实际上,我想您只需要正确引用Bash。
rename "s/^WrongID_/RightId_/" dir/WrongID_Another\ ID\ With\ Spaces_*.*
while read -p dir wrong rest right; do
    rename "s/^${wrong}_/${right}_/" "$dir/${wrong}_${rest}_"*.*
done <<\____
    one    few     other   many
    two    theyre  stuff   there
    three  grammer correct grammar
____
import subprocess
import glob

for dir, wrong, rest, right in (
        ('one',   'few',     'other',   'many'),
        ('two',   'theyre',  'stuff',   'there'),
        ('three', 'grammer', 'correct', 'grammar')):
    subprocess.run(['rename', 's/^{0}_/{1}_/'.format(wrong, right)] +
        glob.glob('{0}/{1}_{2}_*.*'.format(dir, wrong, rest))])