python 使用正则表达式删除命令 subprocess.call

python remove command subprocess.call with regex

我正在尝试从 linux 中的 python 执行 rm 命令,如下所示

remove_command = [find_executable(
            "rm"), "-rf", "dist/", "python_skelton.egg-info", "build/", "other/*_generated.py"]
print('Removing build, dist, python_skelton.egg-
if subprocess.call(remove_command) != 0:
  sys.exit(-1)

目录已成功删除,但正则表达式模式 other/*_generated.py 不会删除相关的 _generated.py 文件。

如何使用正则表达式从 python 脚本中删除这些文件?

这不能按您预期的方式工作的原因是您的模式没有扩展,而是被解释为乱码文件名 "other/*_generated.py"。发生这种情况是因为您依赖于所谓的 glob pattern expansion.

glob 模式通常由 shell 扩展,但由于您在不使用 shell 的情况下调用 rm 命令,您将不会“自动”完成此操作。我可以看到两种明显的处理方法。

在调用 subprocess

之前扩展 glob

这可以做到,使用 Python 标准库 glob 实现:

import glob

remove_command = [find_executable("rm"), "-rf", "dist/", "python_skelton.egg-info", 
                  "build/"] + glob.glob("other/*_generated.py")
subprocess.call(remove_command)

使用shell扩展glob

为此,您需要将 shell=True 传递给 subprocess.call。而且,一如既往,在使用 shell 时,我们应该将命令作为单个字符串而不是列表传递:

remove_command = [find_executable("rm"), "-rf", "dist/", "python_skelton.egg-info", 
                  "build/", "other/*_generated.py"]
remove_command_string = " ".join(remove_command) # generate a string from list
subprocess.call(remove_command_string, shell=True)

这两种方法都有效。请注意,如果您允许用户输入,则应避免使用 shell=True,因为它是一个安全漏洞,可用于执行任意命令。但是,在当前的用例中,情况似乎并非如此。