python - 使用 Python 通过排除隐藏文件来对两个目录执行 diff

标签 python bash diff

我正在尝试编写一个在两个目录上执行 diff -r 的 Python 脚本。我想排除目录中的隐藏文件。

这是我所拥有的。

source = "/Users/abc/1/"
target = "/Users/abc/2/"
bashCommand = 'diff -x ".*" -r ' + source + ' ' + target
# Below does not work either
# bashCommand = "diff -x '.*' -r " + source + ' ' + target

import subprocess

process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if output:
    print "Directories do not match: " + output
else:
    print "Directories match"

我知道我应该使用 -x '.*' 来忽略点文件。我看了this所以帖子。但这没有帮助。我该如何写这一行?

bashCommand = 'diff -x ".*" -r ' + source + ' ' + target

编辑1: 我也试过了,还是不行

pat = "-x \".*\""
bashCommand = "diff " + pat + " -r " + source + " " + target
print bashCommand

当我打印输出并手动运行命令时,它按预期工作。但是 Python 脚本没有产生期望的结果

$python BashCommand.py
diff -x ".*" -r /Users/abc/1/ /Users/abc/2/
Directories do not match: Only in /Users/abc/1/: .a


$diff -x ".*" -r /Users/abc/1/ /Users/abc/2/
$

最佳答案

在 bash 中,单引号和双引号的含义不同。来自 Difference between single and double quotes in Bash

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes.

对于双引号:

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

因此,您的 ".*" 在传递 diff 之前会被扩展。尝试切换引号

bashCommand = "diff -x '.*' -r " + source + ' ' + target

编辑

Popen 通常不使用 shell 来执行您的命令(除非您传递 shell=True),因此您实际上根本不需要转义该模式:

>>> subprocess.Popen(['diff', '-x', "'.*'", '-r', 'a', 'b'])
<subprocess.Popen object at 0x10c53cb50>
>>> Only in a: .dot

>>> subprocess.Popen(['diff', '-x', '.*', '-r', 'a', 'b'])
<subprocess.Popen object at 0x10c53cb10>

关于python - 使用 Python 通过排除隐藏文件来对两个目录执行 diff,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48177847/

相关文章:

git - 如何使用 git diff 创建两个电子表格的可读差异?

shell - 忽略 diff 中的具体差异

python - 逆变换预测结果

python - 使用 Groupby 时调用具有多个参数的函数

python - PyTorch FasterRCNN 类型错误 : forward() takes 2 positional arguments but 3 were given

perl - 如何使用 perl 命令从 URL 读取查询参数值

json - 是否存在针对两种JSON之间差异的既定表示形式?

python - HTTP header 被 `urllib3.exceptions.HeaderParsingError: [MissingHeaderBodySeparatorDefect()], unparsed data` 切成两半

linux - 如何从 shell/bash 脚本中更改 linux 上的桌面墙纸

bash - 等待陷阱后退出