私は現在、Python を自己学習しており、最初のシェル スクリプトを作成中です。「md5hash」による重複ファイル認識機能を備えた Linux ファイル検索シェルスクリプトです。実際のプロジェクトではなく、学習目的でのみ作成されています。
これが私のコードです:
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.非推奨の os.popen() を subprocess.Popen() に置き換えるようにアドバイスされました
それでも、私はそれを行う方法の手がかりがありません。ここのstackoverflowにすでに存在することがわかったいくつかのソリューションを試しましたが、私のケースでは機能しないようで、すべてが何らかのエラーを生成します。たとえば、次のように処理します。
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. このプログラムをトップ (ルート) から検索できるようにするにはどうすればよいですか?
検索パスに「/」を入力すると、PermissionError: [Errno 1] Operation not permitted: '/proc/1871/map_files'
Does my script need sudo privilegies?というメッセージが表示されます。
私はインターネットを使って Python を独学で学ぼうとしています。ご協力いただきありがとうございます!