pythononubuntu
① ubuntu python怎麼作為守護進程一直運行
測試程序
先寫一個測試程序,用於輸出日誌和列印到控制台。
#-*- coding: utf-8 -*-
import logging
import time
from logging.handlers import RotatingFileHandler
def func():
init_log()
while True:
print "output to the console"
logging.debug("output the debug log")
logging.info("output the info log")
time.sleep(3);
def init_log():
logging.getLogger().setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
# add log ratate
Rthandler = RotatingFileHandler("backend_run.log", maxBytes=10 * 1024 * 1024, backupCount=100,
encoding="gbk")
Rthandler.setLevel(logging.INFO)
# formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger().addHandler(Rthandler)
if __name__ == '__main__':
func()
後台啟動Python腳本
可以使用下面的命令來啟動上面的腳本,讓Python在後台運行。
nohup python -u main.py > test.out 2>&1 &
來解釋一下這幾個命令的參數。這一段來自
其中 0、1、2分別代表如下含義:
0 – stdin (standard input)
1 – stdout (standard output)
2 – stderr (standard error)
nohup python -u main.py > test.out 2>&1 &
nohup+最後面的& 是讓命令在後台執行
>out.log 是將信息輸出到out.log日誌中
2>&1 是將標准錯誤信息轉變成標准輸出,這樣就可以將錯誤信息輸出到out.log 日誌裡面來。
運行命令後,會返回一個pid。像下面這樣:
[1] 9208
後續可以學習Hadoop它們,把pid存起來,到時候stop的時候就把它殺掉。
跟蹤輸出文件變化
為了驗證腳本可以在後台繼續運行,我們退出當前會話。然後重新連接一個Session,然後輸入下面的命令來跟蹤文件的輸出:
tail -f test.out
輸出內容如下:
output to the console
2017-03-21 20:15:02,632 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:02,632 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:05,635 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:05,636 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:08,637 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:08,638 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:11,640 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:11,642 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:14,647 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:14,647 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:17,653 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:17,654 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:20,655 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:20,656 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:23,661 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:23,661 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:26,665 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:26,666 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:29,670 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:29,671 main.py[line:12] INFO output the info log
說明我們的腳本確實在後台持續運行。
結束程序
可以直接通過之前的那個pid殺掉腳本,或者可以通過下面的命令查找pid。
ps -ef | grep python
輸出的內容如下:
root 1659 1 0 17:40 ? 00:00:00 /usr/bin/python /usr/lib/python2.6/site-packages/ambari_agent/AmbariAgent.py start
root 1921 1659 0 17:40 ? 00:00:48 /usr/bin/python /usr/lib/python2.6/site-packages/ambari_agent/main.py start
user 8866 8187 0 20:03 ? 00:00:06 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
root 9208 8132 0 20:12 pts/16 00:00:00 python -u main.py
root 9358 8132 0 20:17 pts/16 00:00:00 grep --color=auto python
可以看到我們的pid是9208,調用kill殺掉就可以了。
kill -9 9208
編寫啟動及停止腳本
啟動腳本
#!/bin/sh
pid=`ps -ef|grep "python -u main.py"| grep -v "grep"|awk '{print $2}'`
if [ "$pid" != "" ]
then
echo "main.py already run, stop it first"
kill -9 ${pid}
fi
echo "starting now..."
nohup python -u main.py > test.out 2>&1 &
pid=`ps -ef|grep "python -u main.py"| grep -v "grep"|awk '{print $2}'`
echo ${pid} > pid.out
echo "main.py started at pid: "${pid}
停止腳本
#!/bin/sh
pid=`ps -ef|grep "python -u main.py"| grep -v "grep"|awk '{print $2}'`
if [ "$pid" != "" ]
then
kill -9 ${pid}
echo "stop main.py complete"
else
echo "main.py is not run, there's no need to stop it"
fi
稍後我會把實例代碼上傳到資料共享裡面。
② ubuntu下python用什麼軟體
(一)wxpython的安裝
Ubuntu下的安裝,還是比較簡單的。
1234567891011121314
#使用:apt-cache search wxpython 測試一下,可以看到相關信息dizzy@dizzy-pc:~/Python$ apt-cache search wxpythoncain - simulations of chemical reactionscain-examples - simulations of chemical reactionscain-solvers - simulations of chemical reactionsgnumed-client - medical practice management - Client... #這樣的話,直接使用: sudo apt-get install python-wxtools 即可安裝dizzy@dizzy-pc:~/Python$ sudo apt-get install python-wxtools[sudo] password for dizzy:Reading package lists... DoneBuilding dependency tree...
測試是否安裝成功。進入Python,import wx 不報錯,即可
123456
dizzy@dizzy-pc:~/Python$ pythonPython 2.7.3 (default, Apr 20 2012, 22:44:07)[GCC 4.6.3] on linux2Type "help", "right", "credits" or "license" for more information.>>> import wx>>>
(二)顯示出一個窗口
1234567891011121314
#!/usr/bin/python#coding:utf-8 import wx def main(): app = wx.App() win = wx.Frame(None) win.Show() app.MainLoop() if __name__ == '__main__': main()#這便是一個最簡單的可視化窗口的實現
(三)添加可視化組建及簡單布局#coding:utf-8 import wx def main(): app = wx.App() win = wx.Frame(None,title='NotePad',size=(440,320)) #很明顯,title就是標題,size就是大小 bt_open = wx.Button(win,label='open',pos=(275,2),size=(80,30)) bt_save = wx.Button(win,label='save',pos=(355,2),size=(80,30)) #label就是按鈕顯示的標簽,pos是控制項左上角的相對位置,size就是控制項的絕對大小 text_title = wx.TextCtrl(win,pos=(5,2),size=(265,30)) text_content = wx.TextCtrl(win,pos=(5,34),size=(430,276),style=wx.TE_MULTILINE|wx.HSCROLL) #style樣式,wx.TE_MULTILINE使其能夠多行輸入,wx.HSCROOL使其具有水平滾動條 win.Show() app.MainLoop() if __name__ == '__main__': main() #做過桌面軟體開發的,對這個肯定很熟悉。#由於之前學過一點VB,VC,Delphi等,學起來感覺很簡單。#將wx提供的控制項添加到某個Frame上,並進行各自的屬性設置即可完成#由於文本控制項的size屬性,設置的為絕對值。這樣就會有一些問題......
(四)界面布局管理
由於之前的控制項直接綁定在Frame上,這樣會有一些問題。下面將使用Panel面板進行管理。
28293031323334353637383940
## 當然,之前說將各種控制項的位置都寫成絕對位置和大小,會有一些問題。這是不對的## 有時需要動態布局,而有時則需要靜態布局 import wx def main(): #創建App app = wx.App() #創建Frame win = wx.Frame(None,title='NotePad',size=(440,320)) win.Show() #創建Panel panel = wx.Panel(win) #創建open,save按鈕 bt_open = wx.Button(panel,label='open') bt_save = wx.Button(panel,label='save') #創建文本框,文本域 text_filename = wx.TextCtrl(panel) text_contents = wx.TextCtrl(panel,style=wx.TE_MULTILINE|wx.HSCROLL) #添加布局管理器 bsizer_top = wx.BoxSizer() bsizer_top.Add(text_filename,proportion=1,flag=wx.EXPAND) bsizer_top.Add(bt_open,proportion=0,flag=wx.LEFT,border=5) bsizer_top.Add(bt_save,proportion=0,flag=wx.LEFT,border=5) bsizer_all = wx.BoxSizer(wx.VERTICAL) #wx.VERTICAL 橫向分割 bsizer_all.Add(bsizer_top,proportion=0,flag=wx.EXPAND|wx.LEFT,border=5) bsizer_all.Add(text_contents,proportion=1,flag=wx.EXPAND|wx.ALL,border=5) panel.SetSizer(bsizer_all) app.MainLoop() if __name__ == '__main__': main() #這個是動態布局。當然這只是一個視圖而已。#這只是個表面而已,靈魂不在此!
(五)添加控制項的事件處理
直接上代碼。
#!/usr/bin/python#coding:utf-8 import wx def openfile(evt): filepath = text_filename.GetValue() fopen = file(filepath) fcontent = fopen.read() text_contents.SetValue(fcontent) fopen.close() def savefile(evt): filepath = text_filename.GetValue() filecontents = text_contents.GetValue() fopen = file(filepath,'w') fopen.write(filecontents) fopen.close() app = wx.App()#創建Framewin = wx.Frame(None,title='NotePad',size=(440,320))#創建Panelpanel = wx.Panel(win)#創建open,save按鈕bt_open = wx.Button(panel,label='open')bt_open.Bind(wx.EVT_BUTTON,openfile) #添加open按鈕事件綁定,openfile()函數處理bt_save = wx.Button(panel,label='save')bt_save.Bind(wx.EVT_BUTTON,savefile) #添加save按鈕事件綁定,savefile()函數處理#創建文本框,文本域text_filename = wx.TextCtrl(panel)text_contents = wx.TextCtrl(panel,style=wx.TE_MULTILINE|wx.HSCROLL)#添加布局管理器bsizer_top = wx.BoxSizer()bsizer_top.Add(text_filename,proportion=1,flag=wx.EXPAND,border=5)bsizer_top.Add(bt_open,proportion=0,flag=wx.LEFT,border=5)bsizer_top.Add(bt_save,proportion=0,flag=wx.LEFT,border=5) bsizer_all = wx.BoxSizer(wx.VERTICAL)bsizer_all.Add(bsizer_top,proportion=0,flag=wx.EXPAND|wx.LEFT,border=5)bsizer_all.Add(text_contents,proportion=1,flag=wx.EXPAND|wx.ALL,border=5) panel.SetSizer(bsizer_all) win.Show()app.MainLoop() 47,0-1 Bot ######################################################## 打開,保存功能基本實現,但還存在很多bug。 ## 怎麼也算自己的第二個Python小程序吧!! # ###########################################################################
(六)ListCtrl列表控制項的使用示例
ListCtrl這個控制項比較強大,是我比較喜歡使用的控制項之一。
下面是list_report.py中提供的簡單用法:
import wximport sys, glob, randomimport data class DemoFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "wx.ListCtrl in wx.LC_REPORT mode", size=(600,400)) il = wx.ImageList(16,16, True) for name in glob.glob("smicon??.png"): bmp = wx.Bitmap(name, wx.BITMAP_TYPE_PNG) il_max = il.Add(bmp) self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT) self.list.AssignImageList(il, wx.IMAGE_LIST_SMALL) # Add some columns for col, text in enumerate(data.columns): self.list.InsertColumn(col, text) # add the rows for item in data.rows: index = self.list.InsertStringItem(sys.maxint, item[0]) for col, text in enumerate(item[1:]): self.list.SetStringItem(index, col+1, text) # give each item a random image img = random.randint(0, il_max) self.list.SetItemImage(index, img, img) # set the width of the columns in various ways self.list.SetColumnWidth(0, 120) self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE) self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE) self.list.SetColumnWidth(3, wx.LIST_AUTOSIZE_USEHEADER) app = wx.PySimpleApp()frame = DemoFrame()frame.Show()app.MainLoop()
如何獲取選中的項目?
最常用的方法就是獲取選中的第一項:GetFirstSelected(),這個函數返回一個int,即ListCtrl中的項(Item)的ID。
還有一個方法是:GetNextSelected(itemid),獲取指定的itemid之後的第一個被選中的項,同樣也是返回itemid。
③ ubuntu怎麼安裝python-yaml
Python三種內建數據結構——列表、元組字典依:列表: 列表list處理組序項目數據結構即列表存儲序列項目, Python每項目間用逗號割 列表項目應該包括括弧Python知道指明列表看列表字元串數字即包含種類
④ ubuntu16.04中怎樣運行編好的python
在終端中輸入 vim --version 查看是否支持 python,如果看到 +python,請關閉本頁面;看到 -python 相信你苦惱多時了,往下看吧!
沒辦法只能安裝 py2 包(http://packages.ubuntu.com/search?suite=default§ion=all&arch=any&keywords=-py2&searchon=names),以 nox 為例,在終端輸入 sudo apt-get install vim-nox-py2
安裝完成後在查看是不是支持 python,顯然從 +python3 換成了 +python。你想要兩個都要加號,給你一個眼神。
sudo update-alternatives --config vim 可以讓你在 python 和 python3 之間切換,如圖 1 就是 python3,2 就是 python了。
⑤ ubuntu安裝python3.5的問題
python3.5你已經安裝了只是部分包出現了問題,先卸了python3.5及其包再重裝試試
⑥ 菜鳥求教關於ubuntu下python的一個問題,python沒定義
在python shell下,是不是已經輸入了python,進入了類似下面的界面?
如果是的話,應該輸入python的語句。
$python
Python2.6.6(r266:84292,Oct122012,14:23:48)
[GCC4.4.620120305(RedHat4.4.6-4)]onlinux2
Type"help","right","credits"or"license"formoreinformation.
>>>
⑦ ubuntu 下怎樣安裝python
1.先檢查當前系統中是否已經安裝python,直接使用python -V查看
⑧ ubuntu下python編程
def fib(n):
a,b=0,1
while b<n:
print b,
a,b = b,a+b
fib(10)
Python的強制縮進是要時刻注意的。
⑨ 在ubuntu上安裝python編輯器
你安裝上去的只是個運行環境,你只需要打開終端,輸入"python"就可以運行你的python命令了。
mypc@zhao:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "right", "credits" or "license" for more information.
>>> print "Hello world!"
Hello world!
>>>