samedi 18 juin 2016

Python- How do i use Linux terminal commands like CD and LS?


How do i add terminal commands to my Python script? I have a huge folder of images/videos/folders with more images/videos, and i want to organize them in a HTML file (FirstPage.html).

The script first lists all the files in the directory:

def listFiles():
  command = "ls"
  output = Popen(command, stdout=PIPE) #This is the only way i found to run LS in terminal and get the output
  x = str(output.stdout.read())
  x = x[2:-3]
  x += (" ")
  x = re.sub(r"\n", " ", x)
  y = ""
  finalLIST = list()
  for o in x:
    if o == " ":
      finalLIST.append(str(y))
      y = ""
    else:
      y += o
  return finalLIST #returns a list with all files in the current directory

Then checks if the file is a image or a video, and if its a video, it adds to the HTML file:

<video controls>
  <source src="videoName.mp4" type="video/WebM/mp4">
  <source src="videoName.ogg" type="video/ogg">
  Video not suported!
</video>

and if its a image it adds:

<img src="ImageName.jpg" alt="image"/>

The code is:

def organize():
    DIRECTORIES = listFiles()
    IMAGE = [".png", ".jpg"]
    VIDEO = [".webm", ".mp4"]
    for x in DIRECTORIES:
       if not re.search(".", x):
          #This means that it is a directory
          #I want to CD into this directory and run listFiles() and then organize() it. How i do it?
     else:
         for y in IMAGE:
             ADDimg = "n<img src="" + x + "" alt="imagem"/>n"
             if re.search(y, x):
                 with open(FirstPage.html) as f:
                     for line in f:
                         if line = "<!--IMAGES-->":
                             f.write(ADDimg)
                         break
                     f.write(ADDimg)
         for y in VIDEO:
             ADDvideo = """n<video controls>
                   <source src="""" + x
             """" type="video/WebM/mp4">
                   <source src="video.ogg" type="video/ogg/WebM">
                   Video not suported!
                </video>n
                """
             if re.search(y, x):
                with open(FirstPage.html) as f:
                for line in f:
                     if line = "<!--VIDEOS-->":
                     f.write(ADDvideo)
                     break

this is FirstPag.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>The first page</title>
</head>
<body>
  <!--IMAGES-->


  <!--VIDEOS-->
</body>
</html>

I want this script to list the files in the directory, add all images/ videos that are there to the HTML file, then cd into the folders there, and do the same thing, recursively. Any sugestions?

Thanks!


Aucun commentaire:

Enregistrer un commentaire