我目前正在自学Python,我正在编写我的第一个shell脚本。它是一个linux文件搜索shell-脚本,与‘md5散列’的重复文件识别。它仅仅是为了学习的目的,而不是真正的项目。
这是我的密码:
from subprocess import Popen, PIPE
import os
def index(directory):
stack = [directory]
files = []
while stack:
directory = stack.pop()
for file in os.listdir(directory):
fullname = os.path.join(directory, file)
if search_term in fullname:
files.append(fullname)
if os.path.isdir(fullname) and not os.path.islink(fullname):
stack.append(fullname)
return files
from collections import defaultdict
def check(directory):
files = index(directory)
if len(files) < 1:
print("No file(s) meets your search criteria")
else:
print ("List of files that match your criteria:")
for x in files:
print (x)
print ("-----------------------------------------------------------------")
values = []
for x in files:
cmd = ['md5sum', x]
proc = Popen(cmd, stdout=PIPE)
(out, err) = proc.communicate()
a = out.split(' ', 1)
values.append(a[0])
proc.stdout.close()
stat = os.waitpid(proc.pid, 0)
D = defaultdict(list)
for i,item in enumerate(values):
D[item].append(i)
D = {k:v for k,v in D.items() if len(v)>1}
for x in D:
if len(D[x]) > 1:
print ("File", files[D[x][0]], "is same file(s) as:")
for y in range(1, len(D[x])):
print (files[D[x][y]])
search_term = input('Enter a (part of) file name for search:')
a = input('Where to look for a file? (enter full path)')
check(a)我对守则的问题:
1.有人建议我用subprocess.Popen()代替不推荐的os.popen()
但我不知道该怎么做。我尝试了一些我已经在堆栈溢出中找到的解决方案,但是似乎没有一个解决方案适用于我的情况,而且每个解决方案都会产生某种错误。例如,像这样处理它:
from subprocess import Popen, PIPE
...
cmd = ['md5sum', f]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
proc.stdout.close()
stat = os.waitpid(proc.pid, 0)我得到了NameError: global name 'subprocess' is not defined错误。
我真的迷上了这个,所以我们很感谢你提供的任何帮助。
2.如何使该程序能够从顶部(根)进行搜索?
如果我输入搜索路径的"/“,我得到脚本需要sudo特权的PermissionError: [Errno 1] Operation not permitted: '/proc/1871/map_files'吗?
我正试图通过使用互联网来学习Python。谢谢你的帮忙!
发布于 2013-10-24 19:52:18
1.如果使用from module import variable语法,则可以直接访问variable,在本例中:
from subprocess import Popen, PIPE
proc = Popen(cmd, stdout=PIPE)如果使用import module语法,则需要添加模块名(正如在代码中所做的那样):
import subprocess
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)有关导入的更多信息,我推荐文章对进口的理解与思考。
2.文件系统上的某些文件只能作为根文件读取,例如/proc/目录中的一些文件。要读取它们,您的Python脚本需要根访问,例如通过sudo。
https://stackoverflow.com/questions/19575175
复制相似问题