0

I'm trying to do this, to get the content of the clipboard

clipboard_data = os.system("pbpaste")

But this doesn't work! Not only does it not store whatever was in the clipboard (some text) in the var (returns 0) but it outputs the result of the command on the screen.

How can I make it work how I want?

3 Answers3

4

You should to look into what's offered in the subprocess module for Python. In version 2.7 and later you can achieve what you want with the following, for example:

from subprocess import check_output
clipboard_data = check_output(["pbpaste"])

... or in earlier versions do:

from subprocess import Popen, PIPE
clipboard_data = Popen(["pbpaste"], stdout=PIPE).communicate()[0]

That's missing some error checking, but you get the idea...

Mark Longair
  • 446,582
  • 72
  • 411
  • 327
1

Regardless of what you're trying to achieve (I'm not familiar with pbpaste and IMHO there are better ways to access the clipboard), os.system returns the exit status of the process it's invoking, not its standard output.

You should use subprocess.Popen (with its communicate method) to get the standard output.

Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
-1

A simple method is to use the

f = os.popen(command)

method, it returns a file like object and then you can use the method f.readline() to return a string. The method is quite simple though and shouldn't be used to process large amounts of data because it uses alot of the computers cpu power.

Picaxmad
  • 23
  • 4