【问题标题】:How do i use Linux terminal commands like CD and LS? [duplicate]我如何使用像 CD 和 LS 这样的 Linux 终端命令? [复制]
【发布时间】:2016-10-20 09:42:15
【问题描述】:

如何将终端命令添加到我的 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 到那里的文件夹中,然后递归地做同样的事情。有什么建议吗?

谢谢!

【问题讨论】:

标签: python linux html python-3.5


【解决方案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 来检查目录。

可以结合以上命令进行递归目录遍历。

【讨论】:

  • 如果您认为此答案有助于解决您的问题,请单击绿色复选标记将其标记为“已接受”。这将有助于社区将注意力集中在未回答的问题上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2023-02-01
  • 1970-01-01
  • 2013-02-20
  • 2020-11-11
  • 2011-11-30
  • 1970-01-01
相关资源
最近更新 更多