How do i use Linux terminal commands like CD and LS?
本问题已经有最佳答案,请猛点这里访问。
如何将终端命令添加到Python脚本中?我有一个包含更多图片/视频的图片/视频/文件夹的大文件夹,我想把它们组织成一个HTML文件(firstpage.html)。
脚本首先列出目录中的所有文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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"\ ","", 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文件:
1 2 3 4 5 | <video controls> <source src="videoName.mp4" type="video/WebM/mp4"> <source src="videoName.ogg" type="video/ogg"> Video not suported! </video> |
如果它是一个图像,它会加上:
1 | <img src="ImageName.jpg" alt="image"/> |
代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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 =" <img src="" + x +"" alt="imagem"/> " 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 =""" <video controls> <source src="""" + x """" type="video/WebM/mp4"> <source src="video.ogg" type="video/ogg/WebM"> Video not suported! </video> """ if re.search(y, x): with open(FirstPage.html) as f: for line in f: if line ="<!--VIDEOS-->": f.write(ADDvideo) break |
这是firstpag.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>The first page</title> </head> <body> <!--IMAGES--> <!--VIDEOS--> </body> </html> |
我希望这个脚本列出目录中的文件,将所有在那里的图像/视频添加到HTML文件中,然后将CD放到那里的文件夹中,递归地执行相同的操作。有什么建议吗?
谢谢!
不要对语言库中存在的东西执行
您可以这样使用它:
1 2 3 | from os import listdir from os.path import isfile, join files = [f for f in listdir(mypath) if isfile(join(mypath, f))] |
同样,您可以使用
您可以组合上述命令来进行递归目录遍历。