我有這段代碼,我希望可以將三個分割命令組合成一行,但我不知道如何組合:from __future__ import print_function # Must be first importimport subprocess32 as spdef get_mouse_coordinates(): ''' Get mouse co-ordinates with xdotool: $ xdotool getmouselocation x:4490 y:1920 screen:0 window:65011722 ''' command_line_list = ['xdotool', 'getmouselocation'] pipe = sp.Popen(command_line_list, stdout=sp.PIPE, stderr=sp.PIPE) text, err = pipe.communicate() # This performs .wait() too print("returncode of subprocess:",pipe.returncode) if text: x, y, z = text.split(' ',2) # Grab 'x:9999' 'y:9999' 'junk' x_ret = x.split(':')[1] # Grab right of 'x:9999' y_ret = y.split(':')[1] # Grab right of 'y:9999' print("standard output of subprocess:") print(text,'x-offset:',x_ret,'y-offset:',y_ret) return x_ret, y_ret if err: print("standard error of subprocess:") print(err) return 100, 100可能非常明顯,但以下是三行代碼:x, y, z = text.split(' ',2) # Grab 'x:9999' 'y:9999' 'junk'x_ret = x.split(':')[1] # Grab right of 'x:9999'y_ret = y.split(':')[1] # Grab right of 'y:9999'如果您好奇,請在終端中輸出:returncode of subprocess: 0standard output of subprocess:x:3400 y:558 screen:0 window:23073340 x-offset: 3400 y-offset: 558
1 回答

子衿沉夜
TA貢獻1828條經(jīng)驗 獲得超3個贊
一種方法是使用正則表達式。本質上,您只是想提取數(shù)字,因此模式非常簡單:
? ? import re
? ??
? ? x, y, screen, window = re.findall("[0-9]+", text)
請注意,如果數(shù)字可以為負數(shù),您將需要一個稍長的模式(但似乎在您的情況下,它們不會):
? ? import re
? ??
? ? x, y, screen, window = re.findall("[-+]?[0-9]+", text)
正則表達式模塊的文檔:https ://docs.python.org/3/library/re.html
您還可以使用列表理解:
? ? x, y, screen, window = [tok.split(":")[1] for tok in text.split(" ")]
添加回答
舉報
0/150
提交
取消