我如何使用CD和LS等Linux终端命令?

时间:2016-06-18 18:39:45

标签: python linux html5 python-3.5

如何将终端命令添加到我的Python脚本中? 我有一个包含更多图像/视频的图像/视频/文件夹的大文件夹,我想将它们组织在一个HTML文件中(FirstPage.html)。

该脚本首先列出目录中的所有文件:

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

然后检查文件是图像还是视频,如果是视频,则会添加到HTML文件中:

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

如果是它添加的图像:

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

代码是:

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

这是FirstPag.html:

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


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

我希望这个脚本列出目录中的文件,将那里的所有图像/视频添加到HTML文件中,然后cd进入那里的文件夹,并以递归方式执行相同的操作。任何sugestions?

谢谢!

1 个答案:

答案 0 :(得分:1)

不要对语言库中存在的内容执行cd / ls命令:os.listdir()

你可以像这样使用它:

from os import listdir
from os.path import isfile, join
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]

同样,您可以使用isdir来检查目录。

您可以组合上述命令来进行递归目录遍历。