How to take screenshot of the screen in Python?

Asked

Viewed 5,651 times

4

I would like to make a program that screenshots the screen ( screen photo) in Python.

I found the following code:

import pyscreenshot as ImageGrab

if __name__ == "__main__":
    # fullscreen
    im=ImageGrab.grab()
    im.show()

The code does nothing (apparently gets stuck)!

What does it mean: if __name__ == "__main__":?

Linux Backbox Usage

  • 1

    Here worked. On your second question: http://answall.com/questions/92586/no-final-do-c%C3%b3digo-para-que-serve-a-express%C3%a3o-if-name-main

1 answer

5


First if you have not installed the module, install:

~$ sudo apt-get install python-pip && pip install pyscreenshot

Obs: The pip is a tool for installing Python modules.

To use the pyscreenshot just do:

import pyscreenshot as ImageGrab

def main():
    imagem = ImageGrab.grab()
    imagem.save('screenShot1.jpg', 'jpeg')

if __name__ == "__main__":
    main()

The code above will generate an image JPEG and save her as screenShot1.jpg in the same directory as script.

Your second question is answered here.

  • 1

    I already had everything installed here but still the code does not do anything (it seems to be in loop)... I used python 3.4 in Linux Backbox. I tried to run python 2.7 but : "Import: No module named pyscreenshot" even though Pip install.

  • 1

    Pip apparently installed pyscreenshot only for python 3. How to do the same for python 2.7?

  • 1

    Pip 7.1.0 from /usr/local/lib/python2.7/dist-Packages/Pip-7.1.0-py2.7.Egg (python 2.7)

  • 1

    This code only works in python 2?

  • 1

    @Eds Install the pyscreenshot in Python 2 like this: sudo pip2 install pyscreenshot. See if it works!

  • sudo pip2 install pyscreenshot Requirement already satisfied (use --upgrade to upgrade): pyscreenshot in /usr/local/lib/python2.7/dist-Packages Requirement already satisfied (use --upgrade to upgrade): Easyprocess in /usr/local/lib/python2.7/dist-Packages (from pyscreenshot)

  • I run the code but it does nothing and there are no errors! It seems to be in loop. How strange!

  • @Eds You are running the script thus: python2 nomeScript.py? after executing the script see if a file screenShot1.jpg appears in the same folder as script!

  • No. I was running with Python IDLE 2.7.6. By the command line python2 namesScript.py IT WORKED! I can’t understand the difference!

  • python3 screenshot.py also worked. Any idea why IDLE loops? What a strange thing!

  • @Eds Also I don’t know, maybe IDLE adds some parameter when running script or something like that.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.