3

I need a python script, which will get selected text in an other application with xsel, and then store it in a var.

Thanks

Ambyte
  • 556
  • 5
  • 11

2 Answers2

5

Once you have the text you want selected, run this:

import os

var = os.popen('xsel').read()
print var
TerryA
  • 58,805
  • 11
  • 114
  • 143
c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
1

I'm adding an additional answer based on the fact that os.popen is now considered obsolete. The following code is from the original answer (except variable naming changed for convenience):

out = os.popen("xsel").read()

Now we rewrite it using subprocess.Popen instead of os.popen:

process = subprocess.Popen("xsel", stdout=subprocess.PIPE, universal_newlines=True)
out = process.stdout.read()

It can be simplified as follows:

process = subprocess.Popen("xsel", stdout=subprocess.PIPE, universal_newlines=True)
out, err = process.communicate()

And the best at the end:

out = subprocess.check_output("xsel", universal_newlines=True)

The universal_newlines option, while the name doesn't suggest that, turns the input and output into text strings instead of byte strings, which are the default for subprocess.Popen.

Pavel Šimerda
  • 5,783
  • 1
  • 31
  • 31