2013-03-18 125 views
0

我注意到我有兩種選擇來在Python腳本中寫入Linux中的文件。我可以創建Popen對象並使用shell重定向(例如「>」或「>>」)寫入文件 - 或者我可以使用文件對象(例如open(),write(),close())。Python:使用Popen()與文件對象在Linux中寫入文件

我已經玩了一會兒,注意到如果我需要使用其他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,但我不確定我應該在哪裏去這裏。

回答

2

一般來說,我會寫這樣的:

manifest = open('/dir/test/' + PID + '.tempfile','w') 
p = Popen(['md5sum',filename],stdout=manifest) 
p.wait() 
manifest.close() 

這可避免外殼注入漏洞。你也知道PID,因爲你沒有選擇產生的子shell的PID。

2

編輯:MD5模塊已被棄用(但仍然存在),而不是你應該使用hashlib module

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 module提供相同的工具:

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十六進制消化字符串,可以打印insted的寫出來,以一個文件:

import md5 
# open file to write 
with open('test.txt', mode='ro') as input: 
    print md5.new(input.read()).hexdigest()