pythonremote
『壹』 Appium使用python進行自動化測試問題,webdriver.Remote報編碼錯誤
這游友個是編碼問題,沒有用過Appium,給個建議:
檢查你代碼里的點號、神瞎槐冒號、句號和製表符等,不要出現半形符號神襲。
『貳』 防止 python deamon 進程被幹掉
最近需要在一台 remote 的 gpu 機器上跑 training 的腳本,terminal 不可能一直開著,所以肯定都是要以 daemon 方式來談彎首跑。
眾所周知,最簡單的 daemon 運行的方式就是在命令後加 &,再配合將輸出重定向到一個 log 文件,這樣就可以實現即以 daemon 跑,也能隨時查看 output 和error 相關的信息。比如
不過最近幾天,我發現每次到公司查看昨晚上的任務情況,都發現進程在我下班後不久就被幹掉,output.log 中也沒有任何的錯誤信息。實在是相當詭異。
google 了一番,沒什麼有建設性的意見,一開始以為是不是 & 方式的 daemon 天生有缺陷,還研究半天怎麼用 python fork 出 daemon process。但越試越感覺,可能這個不是主要原因,在玩了幾次 python-daemon 之後,還是決定回到源頭嘗試解決。
其中有一個回答提到了可能因為腳本佔用內存過大導致被系統 kill 掉(OOM),這個時候腳本本身是不會輸出錯誤的。於是就去 /var/log/system.log 里邊兒翻 OOM,結果 OOM 沒翻到到翻到了一個 "Received SIGRTMIN+24 from PID 27041 (kill)." , 繼續 google 了一下發現。這是系統鬧凱進程 systemd 發出的信號,(systemd 可以理解為調度 daemon process 的進程)。
為什麼 systemd 沒事兒會來干我的腳本呢? 因為 systemd 默認會在一個 user detach 的時候,幹掉這個 user 啟動的所有 process,不管你是不是 daemon。所以當我的本地電腦休眠超過一定時間時,遠程的機器自動 logout user, 然後觸發 systemd 幹掉了我的腳本,即便我的腳本有 & 加持。
知道問題的原因那就簡單了,簡單 google 一下就能知道, 我們只含數需要修改 /etc/systemd/logind.conf 中,將 KillUserProcesses=no 反 comment 即可。代表讓 systemd 不要幹掉 user process。
『叄』 如何利用Python嗅探數據包
一提到Python獲取數據包的方式,相信很多Python愛好者會利用linux的libpcap軟體包或利用Windows下的WinPcap可移植版的方式進行抓取數據包,然後再利用dpkt軟體包進行協議分析,我們這里想換一個角度去思考:1.Python版本的pcap存儲內存數據過小,也就是說緩存不夠,在高並發下容易發生丟包現象,其實C版本的也同樣存在這樣的問題,只不過Python版本的緩存實在是過低,讓人很郁悶。2.dpkt協議分析並非必須,如果你對RFC791和RFC793等協議熟悉的話,完全可以使用struct.unpack的方式進行分析。如果你平常習慣使用tcpmp抓取數據包的話,完全可以使用它來代替pcap軟體包,只不過我們需要利用tcpmp將抓取的數據以pcap格式進行保存,說道這里大家一定會想到Wireshark工具,具體命令如下:tcpmpdst10.13.202.116andtcpdstport80-s0-ieth1-w../pcap/tcpmp.pcap-C1k-W5我們首先需要對pcap文件格式有所了解,具體信息大家可以參考其他資料文檔,我這里只說其重要的結構體組成,如下:sturctpcap_file_header{DWORDmagic;WORDversion_major;WORDversion_minor;DWORDthiszone;DWORDsigfigs;DWORDsnaplen;DWORDlinktype;}structpcap_pkthdr{structtimevalts;DWORDcaplen;DWORDlen;}structtimeval{DWORDGMTtime;DWORDmicroTime;}這里需要說明的一點是,因為在Python的世界裡一切都是對象,所以往往Python在處理數據包的時候感覺讓人比較麻煩。Python提供了幾個libpcapbind,這里有一個最簡單的。在windows平台上,你需要先安裝winpcap,如果你已經安裝了Ethereal非常好用。一個規范的抓包過程:importpcapimportdpktpc=pcap.pcap()#注,參數可為網卡名,如eth0pc.setfilter('tcpport80')#設置監聽過濾器forptime,pdatainpc:#ptime為收到時間,pdata為收到數據printptime,pdata#對抓到的乙太網V2數據包(rawpacket)進行解包:p=dpkt.ethernet.Ethernet(pdata)ifp.data.__class__.__name__=='IP':ip='%d.%d.%d.%d'%tuple(map(ord,list(p.data.dst)))ifp.data.data.__class__.__name__=='TCP':ifdata.dport==80:printp.data.data.data一些顯示參數nrecv,ndrop,nifdrop=pc.stats()返回的元組中,第一個參數為接收到的數據包,第二個參數為被核心丟棄的數據包。至於對於如何監控tcpmp生成的pcap文件數據,大家可以通過pyinotify軟體包來實現,如下:classPacker(pyinotify.ProcessEvent):def__init__(self,proct):self.proct=proctself.process=Nonedefprocess_IN_CREATE(self,event):logger.debug("createfile:%sinqueue"%self.process_IF_START_THREAD(event))defprocess_IN_MODIFY(self,event):self.process_IF_START_THREAD(event)logger.debug("modifyfile:%sinqueue"%self.process_IF_START_THREAD(event))defprocess_IN_DELETE(self,event):filename=os.path.join(event.path,event.name)logger.debug("deletefile:%s"%filename)defprocess_IF_START_THREAD(self,event):filename=os.path.join(event.path,event.name)iffilename!=self.process:self.process=filenameself.proct.put(filename)ifself.proct.qsize()>1:try:logger.debug("createconsumerproct.qsize:%s"%self.proct.qsize())consumer=Consumer(self.proct)consumer.start()exceptException,errmsg:logger.error("createconsumerfailed:%s"%errmsg)returnfilenameclassFactory(object):def__init__(self,proct):self.proct=proctself.manager=pyinotify.WatchManager()self.mask=pyinotify.IN_CREATE|pyinotify.IN_DELETE|pyinotify.IN_MODIFYdefwork(self):try:try:notifier=pyinotify.ThreadedNotifier(self.manager,Packer(self.proct))notifier.start()self.manager.add_watch("../pcap",self.mask,rec=True)notifier.join()exceptException,errmsg:logger.error("createnotifierfailed:%s"%errmsg)exceptKeyboardInterrupt,errmsg:logger.error("factoryhasbeenterminated:%s"%errmsg)在獲得要分析的pcap文件數據之後,就要對其分析了,只要你足夠了解pcap文件格式就可以了,對於我們來講只需要獲得TCP數據段的數據即可,如下:classWriter(threading.Thread):def__init__(self,proct,stack):threading.Thread.__init__(self)self.proct=proctself.stack=stackself.pcap_pkthdr={}defrun(self):whileTrue:filename=self.proct.get()try:f=open(filename,"rb")readlines=f.read()f.close()offset=24whilelen(readlines)>offset:self.pcap_pkthdr["len"]=readlines[offset+12:offset+16]try:length=struct.unpack("I",self.pcap_pkthdr["len"])[0]self.stack.put(readlines[offset+16:offset+16+length])offset+=length+16exceptException,errmsg:logger.error("unpackpcap_pkthdrfailed:%s"%errmsg)exceptIOError,errmsg:logger.error("openfilefailed:%s"%errmsg)在獲得TCP數據段的數據包之後,問題就簡單多了,根據大家的具體需求就可以進行相應的分析了,我這里是想分析其HTTP協議數據,同樣也藉助了dpkt軟體包進行分析,如下:defworker(memcache,packet,local_address,remote_address):try:p=dpkt.ethernet.Ethernet(packet)ifp.data.__class__.__name__=="IP":srcip="%d.%d.%d.%d"%tuple(map(ord,list(p.data.src)))dstip="%d.%d.%d.%d"%tuple(map(ord,list(p.data.dst)))ifp.data.data.__class__.__name__=="TCP":tcpacket=p.data.dataiftcpacket.dport==80anddstip==local_address:srcport=tcpacket.sportkey=srcip+":"+str(srcport)iftcpacket.data:ifnotmemcache.has_key(key):memcache[key]={}ifnotmemcache[key].has_key("response"):memcache[key]["response"]=Noneifmemcache[key].has_key("data"):memcache[key]["data"]+=tcpacket.dataelse:memcache[key]["data"]=tcpacket.dataelse:ifmemcache.has_key(key):memcache[key]["response"]=dpkt.http.Request(memcache[key]["data"])try:stackless.tasklet(connection)(memcache[key]["response"],local_address,remote_address)stackless.run()exceptException,errmsg:logger.error("connectremoteremote_addressfailed:%s",errmsg)logger.debug("oldheaders(nonecontent-length):%s",memcache[key]["response"])memcache.pop(key)exceptException,errmsg:logger.error("dpkt.ethernet.Ethernetfailedinworker:%s",errmsg)如果大家只是想單純的獲取IP地址、埠、流量信息,那麼問題就更簡單了,這里只是拋磚引玉。另外再提供一段代碼供參考:importpcap,dpkt,structimportbinasciidefmain():a=pcap.pcap()a.setfilter('udpportrange4000-4050')try:fori,pdataina:p=dpkt.ethernet.Ethernet(pdata)src='%d.%d.%d.%d'%tuple(map(ord,list(p.data.src)))dst='%d.%d.%d.%d'%tuple(map(ord,list(p.data.dst)))sport=p.data.data.sportdport=p.data.data.dport =int(binascii.hexlify(p.data.data.data[7:11]),16)print' :%d,From:%s:%d,To:%s:%d'%( ,src,sport,dst,dport)exceptException,e:print'%s'%en=raw_input()if__name__=='__main__':main()
『肆』 python為何多線程報錯,單線程沒問題
挖,你的csdn懸賞一百分,虧了虧了。
網頁鏈接
上面那個博主文章中的答案應該就能解決,歸根結底,這是com組件在初始化時對待單線程和多線程存在區別所致(python默認只初始化單線程的COM組件)。
方便不小心點進來的朋友直接粘貼答案如下:
查了一下,在線程所在文件中加入 import pythoncom
每個進程執行時需要加上一句:pythoncom.CoInitialize()就可以解決。
『伍』 Python在driver = webdriver.Remote('地址', desired_caps)就報錯,是什麼原因
java沒有正確安裝
『陸』 python使用Flask框架獲取用戶IP地址的方法
主要介紹了python使用Flask框架獲取用戶IP地址的方法,實例分析了Python使用Flask框架remote_addr獲取IP的`技巧,非常具有實用價值,需要的朋友可以參考下。
下面的代碼包含了html頁面和python代碼,非常詳細,如果你正使用Flask,也可以學習一下最基本的Flask使用方法。
python代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
from flask import Flask, render_template, request
# Initialize the Flask application
app = Flask(__name__)
# Default route, print user's IP
@app.route('/')
def index():
ip = request.remote_addr
return render_template('index.html', user_ip=ip)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80")
)
html代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<p class="container">
<p class="header">
<h3 class="text-muted">How To Get The IP Address Of The User</h3>
</p>
<hr/>
<p>
You IP address is: <strong>{{user_ip}}</strong>
<p class="header">
<h3 class="text-muted">Code to retrieve the IP</h3>
</p>
<hr/>
<pre>
from flask import Flask, render_template, request
# Initialize the Flask application
app = Flask(__name__)
# Default route, print user's IP
@app.route('/')
def index():
ip = request.remote_addr
return render_template('index.html', user_ip=ip)
</pre>
</p>
</p>
</body>
</html>
希望本文所述對大家的Python程序設計有所幫助。
『柒』 python 實現 在已打開的頁面操作
1、要重寫Remote類,防止session重建,如下:
class ReuseChrome(Remote):
def __init__(self, command_executor, session_id):
self.r_session_id= session_id
Remote.__init__(self, command_executor=command_executor, desired_capabilities={})
def start_session(self, capabilities, browser_profile=None):
if not isinstance(capabilities, dict):
raise InvalidArgumentException("Capabilities must be a dictionary")
if browser_profile:
if "moz:firefoxOptions" in capabilities:
沖團橋 capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded
else:
capabilities.update({'firefox_profile': browser_profile.encoded})
散猛 self.capabilities= options.Options().to_capabilities()
self.session_id= self.r_session_id
self.w3c= False
2、或襲訪問已打開頁面方式:
dr= ReuseChrome(command_executor=old_curl, session_id=sessionid)
其中old_curl需在原來打開的頁面上獲取:
old_curl=dr.command_executor._url #一定要用這個方法,獲取當前地址是行不通的!
sessionid=dr.session_id
『捌』 Python高性能分布式執行框架-Ray
這是別人說的,咱也不敢說,咱也不敢問 ! 了解大致的邏輯就好.你只需要知道他超級牛逼,超級方便
安裝就是簡單的 pip install ray , 需要提醒的就是ray現在只有linux編配卜梁譯版本, windows就別想著用了,為了這,我硬生生把開發環境從windows切到了linux.
首先來看一下最簡單的Ray程序是如何編寫的。
在Ray里,通過Python註解@ray.remote定義remote函數。使用此註解聲明的函數都會自帶一個默認的方法remote,通過此方法發起的函數調用都是以提交分布式任務的方式非同步執行的,函數的返培運回值是一個對象id,弊悉使用ray.get內置操作可以同步獲取該id對應的對象
參考:
高性能分布式執行框架——Ray
取代 Python 多進程!伯克利開源分布式框架 Ray
官方文檔
基於python的高性能實時並行機器學習框架之Ray介紹
『玖』 python里的rc是什麼意思
在Python中,rc通常是指配置文件中的運行時配置(runtime configuration)選項。rc在Linux和Unix系統中是很磨雀常見的一種命名規范,表示運行時的配置文件。
例如,在Python中,一些庫或應用程序可能提供一個名為.pylintrc或者pyproject.toml的配置文件,其中包含有關該庫或應用程序如何運行的選項和參數。在這些配置知棗文件中,rc就代表運行時配置。
另外,有時候rc也可以是指遙控器(remote control)的縮寫,這通常是在處理機器人控制、無線通信搭游拆、自動化等方面的項目中使用的。