【问题标题】:Delete a file with the name given in the promt also with specific extention删除提示中给出的名称以及特定扩展名的文件
【发布时间】:2018-08-14 12:09:38
【问题描述】:
import subprocess

name = raw_input("Enter the name of the file: ")

subprocess.Popen(["find", "-name", "*.spec", "|", "grep", name, "|", "xargs", "rm"], cwd="/opt/blusapphire/app/master/dist", stdout=subprocess.PIPE)

我已经在 python 文件中编写了上面的代码。我的目标是删除一个文件,即 abc.spec

所以当我执行时

python <filename>.py

它会询问文件名。当我给 abc 它应该只删除 abc.spec 文件

但上面的代码给出了以下错误

find: paths must precede expression: abc
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

【问题讨论】:

  • 您的问题可以简化为subprocess.Popen(["echo", "hello", "|", "cat"])

标签: python find subprocess


【解决方案1】:

您的尝试有太多错误的假设,无法全面回答。

  • subprocess 默认不运行shell; |xargs 作为参数传递给 find
  • raw_input() 返回一个带换行符的字符串
  • subprocess.Popen() 确实是错误的工具(可以说 Python 是错误的工具)
  • 您的 shell 命令管道过于复杂;只需使用find 的功能即可

试试这个:

from subprocess import check_cmd  # or run once you upgrade to Python 3.6+

name = raw_input("Enter the name of the file: ")  # or input() once you upgrade to Python 3
name = name.rstrip('\n')

check_cmd(['find', '-name', '*%s*.spec' % name, '-delete'])

需要交互式输入的脚本通常不如接受命令行参数的脚本;使用命令行参数,您可以轻松获取历史记录、制表符补全等,因为这些(很可能)已经是交互式 shell 的功能。

【讨论】:

    【解决方案2】:
      import subprocess
      name = raw_input("Enter the name of the file: ") 
      name = name.rstrip('\n') 
      subprocess.Popen(['find', '-name', '*%s*.spec' % name, '-delete'])
    

    我的问题解决了。

    【讨论】:

    • 使用Popen() 意味着您开始一个进程,但它永远不会正确完成。您通常应该使用用户级包装器之一,而不是 Popen(),除非 check_cmd 等。由于某种原因不足。 (您也有一个复制/粘贴错误,其中name = name.rstrip('\n') 应该单独位于单独的行上。)您基本上没有提供反馈就接受了我的回答,更不用说接受或赞成它了,这让我很不高兴。另请参阅help
    • 从技术上讲,这并不能解决您的问题。这是解决它的另一种方法。您应该在子流程中使用管道基础设施来使您的原始方式工作(尽管这样更好)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2012-06-20
    • 2014-10-18
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    相关资源
    最近更新 更多