2017-08-13 3 views
0

Voici la commande que j'exécute en shell. Je veux obtenir les mêmes résultats en Python. Puis-je le faire en utilisant le module os et comment? J'utilise grep -v ici car certains noms de fichiers ont aussi ce motif. S'il vous plaît noter que je ne veux pas invoquer cela à partir de shell.Répliquer une commande du du modifié en python

du -ah 2> >(grep -v "permission denied") |grep [1-9][0-9]G | grep -v [0-9][0-9]K|grep -v [0-9][0-9]M|sort -nr -k 1| head -50 
+0

'sous-processus d'importation; subprocess.check_output ('du -ah 2>> (grep -v "autorisation refusée") | grep [1-9] [0-9] G | grep -v [0-9] [0-9] K | grep -v [0-9] [0-9] M | sort -nr -k 1 | head -50 ', shell = True) ' –

+0

a oublié d'ajouter ... ne veut pas invoquer de shell .. donc shell = False est ce que j'ai besoin, mais alors comment puis-je utiliser du comme ça? – pulkit

+0

Vous comprendrez. 'subprocess' est le chemin à parcourir. –

Répondre

0

Vous pouvez utiliser ce programme python. Il ne génère aucun processus enfant dans le shell.

#!/usr/bin/env python 

from __future__ import absolute_import 
from __future__ import print_function 
import subprocess 
import os 
import argparse 

def files_larger_than_no_child_process(min_bytes, count): 
    """Return the top count files that are larger than the given min_bytes""" 

    # A list that will have (size, name) tuples. 
    file_info = [] 
    for root, dirs, files in os.walk("."): 
     for f in files: 
      file_path = os.path.abspath(os.path.realpath(os.path.join(root, f))) 
      try: 
       size = os.path.getsize(file_path) 
       # Discard all smaller files than the given threshold 
       if size > min_bytes: 
        file_info.append((size,file_path)) 
      except OSError as e: 
       pass 

    # Sort the files with respect to their sizes 
    file_info = sorted(file_info, key=lambda x: x[0], reverse=True) 

    # Print the top count entries 
    for l in file_info[:count]: 
     print(l[0], " ", l[1]) 

def main(): 
    parser = argparse.ArgumentParser("""Prints the top files that are larger than the 
     given bytes in the current directory recusrively.""") 
    parser.add_argument("min_bytes",help="Print files larger than this value", 
     type=int) 
    parser.add_argument("count",help="Print at most the given number of files", 
     type=int) 
    args = parser.parse_args() 


    files_larger_than_no_child_process(args.min_bytes, args.count) 

if __name__ == "__main__": 
    main() 
+0

j'ai essayé ce code .. mais obtenir l'OSError ci-dessous ... puis j'ai ajouté un essai sauf bloc pour attraper cette exception, mais toujours l'obtenir ... que pensez-vous est le problème ici? – pulkit

+0

Quelle est l'erreur @pulkit –

+0

retraçage (appel le plus récent en dernier): Fichier "/home/aspx/psharma1/scripts/diskusage2.py", ligne 38, à files_larger_than_no_child_processes (100000,50) fichier «/home /aspx/psharma1/scripts/diskusage2.py ", ligne 19, dans files_larger_than_no_child_processes size = os.path.getsize (chemin_fichier) Fichier" /usr/lib64/python2.6/genericpath.py ", ligne 49, dans getsize return os.stat (nom de fichier) .st_size OSError: [Errno 2] Aucun fichier ou répertoire de ce type: './proftp_1.3.5rc4/usr/proftp/proftpd-1.3.5rc4/lib/libltdl/.libs/libltdlc. la ' – pulkit