2013-07-01 77 views
3

我寫了一個腳本來檢索網站的天氣報告,並在早上發送給我的女朋友。使用子流程模塊發送電子郵件在python

使用Gmail。當然,我可以使用我的Postfix服務器發送它。這是腳本。

什麼我不知道是如何使用Popen()函數的情況下有這麼多的參數。

我可以使用該命令發送郵件。

$ mail -s "おお様からの天気予報" [email protected] < foo

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
from bs4 import BeautifulSoup 
import urllib2 
import subprocess 

weather_url = "http://www.weather.com.cn/weather/101020100.shtml" 
f=urllib2.urlopen(weather_url) 
html = f.read() 
soup = BeautifulSoup(html) 

content = soup.title.string 

with open("foo","w") as mail: 
    mail.write(content.encode('utf-8')) 

command_line = 'mail -s "おお様からの天気予報" [email protected] < foo' 

li = command_line.split() 

process = subprocess.Popen(li, shell=True) 

returncode = process.wait() 

天氣報告的內容是在foo文件。有人能告訴我如何使用Popen()這麼多的論據嗎?

我試了很多。

這個腳本似乎不工作。

回答

2

當您使用shell=True你可以傳遞一個參數字符串你並不需要傳遞一個參數列表...

command_line = 'mail -s "おお様からの天気予報" [email protected] < foo' 
process = subprocess.Popen(command_line, shell=True) 

或者..你不能使用shell來解釋你的論點,並通過一個列表...

command_line = 'mail -s "おお様からの天気予報" [email protected] < foo' 
li = command_line.split() 
process = subprocess.Popen(li) 

但你不能傳遞一個參數列表使用shell來解釋它。

根據你的命令的性質,我建議將一個字符串傳遞給shell來解釋。 (第一種選擇)

+0

謝謝,快速回復,讓我試試吧 –

+0

你是天才。它像一個魅力。短回覆,但在···馬蒂夫,謝謝,現在我要發送每日天氣報告給我的女朋友使用cron –

+0

如果這對你有幫助,你可以[接受我的回答](http:// meta。 stackexchange.com/a/5235/192545) –

相關問題