[英]Python: Using Popen() versus File Objects to write to a file in linux
我注意到在python腳本中在Linux中寫入文件有兩種選擇。 我可以創建一個Popen對象並使用shell重定向(例如“>”或“ >>”)將其寫入文件,也可以使用文件對象(例如open(),write(),close())。
我已經玩了很短一段時間,並且注意到如果需要使用其他Shell工具,使用Popen涉及的代碼更少。 例如,下面我嘗試獲取文件的校驗和,並將其寫入以PID為唯一標識符的臨時文件中。 (我知道如果再次調用Popen,$$會改變,但假裝不需要):
Popen("md5sum " + filename + " >> /dir/test/$$.tempfile", shell=True, stdout=PIPE).communicate()[0]
下面是使用文件對象的(草率編寫的)粗略等效內容。 我使用os.getpid而不是$$,但是我仍然使用md5sum並且必須仍然調用Popen。
PID = str(os.getpid())
manifest = open('/dir/test/' + PID + '.tempfile','w')
hash = Popen("md5sum " + filename, shell=True, stdout=PIPE).communicate()[0]
manifest.write(hash)
manifest.close()
兩種方法都有優點/缺點嗎? 我實際上正在嘗試將bash代碼移植到Python上,並想使用更多的Python,但是我不確定應該采用哪種方式。
一般來說,我會寫類似:
manifest = open('/dir/test/' + PID + '.tempfile','w')
p = Popen(['md5sum',filename],stdout=manifest)
p.wait()
manifest.close()
這樣可以避免任何外殼注入漏洞。 您還知道PID,因為您沒有選擇生成的子外殼的PID。
編輯 :不建議使用md5模塊(但仍然存在),而應使用hashlib模塊
hashlib版本
提交:
import hashlib
with open('py_md5', mode='w') as out:
with open('test.txt', mode='ro') as input:
out.write(hashlib.md5(input.read()).hexdigest())
控制台:
import hashlib
with open('test.txt', mode='ro') as input:
print hashlib.md5(input.read()).hexdigest()
md5版本 Python的md5模塊提供了相同的工具:
import md5
# open file to write
with open('py_md5', mode='w') as out:
with open('test.txt', mode='ro') as input:
out.write(md5.new(input.read()).hexdigest())
如果您只想獲取md5十六進制摘要字符串,則可以將其打印出來,以將其寫出到文件中:
import md5
# open file to write
with open('test.txt', mode='ro') as input:
print md5.new(input.read()).hexdigest()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.