简体   繁体   中英

using python .subprocess for terminal command

Hi everyone I want to remove all files/folder on a specific folder and to do that I wrote the following code : ( I want to remove all of the file/folders on the directory saved in co_directory except packages_with_....txt files however I got an error

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)'

Is there anyone to help me ? thanks a lot

EDIT **co_directory is global variable**

There are a couple of ways to do this, without using subprocess ,

The os module,

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM