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

1

2 Answers 2

5

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

import os

var = os.popen('xsel').read()
print var
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.