【发布时间】: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 到那里的文件夹中,然后递归地做同样的事情。有什么建议吗?
谢谢!
【问题讨论】:
-
使用
os模块。 -
我导入了re、Popen和PIPE,会检查这个OS模块。
-
不要为了调用终端命令而打开另一个进程,而是使用Python中的函数。分别与How to list all files of a directory in Python 和How do I "cd" in Python? 重复。
-
@0U0p0-0t0o0-0d0a0t0e0 我看到了,你不需要。阅读我提供的链接。
标签: python linux html python-3.5