【问题标题】:using python .subprocess for terminal command使用 python .subprocess 作为终端命令
【发布时间】:2013-08-25 09:12:11
【问题描述】:

大家好,我想删除特定文件夹中的所有文件/文件夹,为此我编写了以下代码:(我想删除保存在 co_directory 中的目录中的所有文件/文件夹,packages_with_.... txt 文件,但是我得到一个错误

def remove_file():

    remove="sudo rm -rf !(packages_with_diff_branches.txt|packages_with_same_branches.txt)"
    p = subprocess.Popen("""
    %s
    %s""" % (co_directory,remove),shell=True , executable='/bin/bash')
    p.wait()





/bin/bash: -c: line 3: syntax error near unexpected token `('
/bin/bash: -c: line 3: `    sudo rm -rf !(packages_with_diff_branches.txt|packages_with_same_branches.txt)'

有人帮我吗?非常感谢

编辑 **co_directory 是全局变量**

【问题讨论】:

    标签: python terminal command subprocess


    【解决方案1】:

    有几种方法可以做到这一点,而无需使用subprocess

    os 模块,

    import os
    
    filesInDir= [ i for i in os.listdir("/path/to/dir") if i != "yourFile.txt" if i! = "yourFile.txt2" ]
    for i in filesInDir:
        os.remove(i)
    

    【讨论】:

    • 感谢您的评论,但如何防止删除我不想删除的文件/
    • @Eday 另外,我不认为-rf 接受!(a|b| 命令,您可能只想这样做,sudo rm !(packages_with_diff_branches.txt|packages_with_same_branches.txt)
    • 感谢您的评论。你是对的。直到我删除 -rf 选项才运行它。再次感谢
    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2019-07-05
    • 2018-09-01
    • 2020-05-18
    • 2018-12-28
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多