iT邦幫忙

0

Ubuntu 中以sudo執行 python3 爬蟲的編碼問題 與 Crontab 排程設定問題

大家好,小弟最近寫了一隻python爬蟲來爬期交所的每日交易資料,然後讓他每天可以更新到我的MySQL資料庫中,環境是Ubuntu 18.04.02 LTS。

在進行測試時,我發現分別以Sudo和直接執行的方式,輸入下面兩段程式碼時,產生的結果一個有報錯一個沒有,請問這可能是什麼原因所產生的呢?

sudo python ~/../home/futures_crawer/institute_daily_crawer_sql.py

https://ithelp.ithome.com.tw/upload/images/20190416/20110872cz0e8lHIrM.jpg

python ~/../home/futures_crawer/institute_daily_crawer_sql.py

https://ithelp.ithome.com.tw/upload/images/20190416/20110872DWMUbeS8b7.jpg


另外還有一個問題想請教,我目前設定了Crontab排程讓爬蟲每天幫我爬資料,我參考了網路上的設定資料做了如下方的設定:

#每日自動爬取台指期法人交易資料 並寫入SQL資料庫
33 17 * * * python ~/../home/futures_crawer/institute_daily_crawer_sql.py ; echo "data has been written" >> /tmp/python_crawer.log

但是我使用 grep CRON /var/log/syslog 看,是顯示有執行指令的不過會有 No MTA installed, discarding output 的警告訊息,而且無法寫入,但我如果直接在CMD執行:

python ~/../home/futures_crawer/institute_daily_crawer_sql.py ; echo "data has been written" >> /tmp/python_crawer.log

它是可以成功寫入MySQL的

請問有大大知道這兩個問題該如何解嗎?感激不盡><

ccutmis iT邦高手 2 級 ‧ 2019-04-16 07:48:26 檢舉
會是權限問題嗎 試試 sudo chmod a+x 你的py檔名
參考: http://linux.vbird.org/linux_basic/0210filepermission.php
huahualiu iT邦新手 2 級 ‧ 2019-04-17 12:33:40 檢舉
不是權限問題,是系統預設python版本與我另外安裝版本不一樣造成的。
謝謝大大~
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
froce
iT邦大師 1 級 ‧ 2019-04-16 08:19:56
最佳解答

1.沒看到你的code,這是編碼問題,詳細得看你程式怎麼寫和linux環境變數才能確定。
2.No MTA installed, discarding output查了一下是你cron執行時發生錯誤,他要寄信給你,但沒郵件伺服器。可以透過將output重新指向來處理。
https://kknews.cc/zh-tw/news/epg24o4.html
https://blog.csdn.net/win_turn/article/details/53000899

huahualiu iT邦新手 2 級 ‧ 2019-04-17 01:05:33 檢舉

感謝大大回復。
第一個問題,我後來發現是VPS系統上面是預設Python2.7,而我的爬蟲是使用python3撰寫的,因此當我下sudo python...時,它會跳回原本系統預設的py2.7執行,所以會產生亂碼。

所以只要我寫

sudo python3 ...........

一切就正常了~~

huahualiu iT邦新手 2 級 ‧ 2019-04-17 12:35:06 檢舉

Crontab 排程無執行問題,第二條連結很有幫助,感恩。

我要發表回答

立即登入回答