Python将.split()的三行合并为一行



我有这样的代码,我希望三个拆分命令可以组合成一行,但我不知道如何:

from __future__ import print_function       # Must be first import
import subprocess32 as sp
def 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: 0
standard output of subprocess:
x:3400 y:558 screen:0 window:23073340
x-offset: 3400 y-offset: 558

正如@zvone所提到的,实现这一点的一种方法是使用regex。本质上,你只是想找出数字,所以模式很简单:

import re

x, y, screen, window = re.findall("[0-9]+", text)

注意,如果数字是负数,你需要一个稍长的模式(但在你的情况下,似乎不会(:

import re

x, y, screen, window = re.findall("[-+]?[0-9]+", text)

regex模块的文档:https://docs.python.org/3/library/re.html

你也可以使用列表理解:

x, y, screen, window = [tok.split(":")[1] for tok in text.split(" ")]

最新更新