42

I am on a Raspberry Pi, and I am using a program called fswebcam, which allows you to take pictures with a webcam.

~$ fswebcam image.jpg

That command if entered in terminal takes a picture and saves it to your computer, however I want to build a simple python program that can access the terminal and execute that same command as I have listed above.

I have tried to import os and use os.system('fswebcam image.jpg') But it isn't working for me.

How can I have python execute terminal commands?

5
  • 5
    Please show some actual code you've tried and the error you got. Commented Jan 1, 2016 at 0:24
  • 9
    is this what you want? stackoverflow.com/questions/89228/… Commented Jan 1, 2016 at 0:42
  • 1
    @KevinGuan Probably. However the subprocess module is preferred. Commented Jan 1, 2016 at 0:56
  • 1
    Terminological note: a terminal is a device (probably a virtual one shown in the window) used by interactive programs, most notably an interactive command interpreter (called shell in Unix jargon). os.system usually uses the same shell but in non-interactive mode. So, fswebcam image.jpg is a shell command, but it isn't related to terminal. Commented Jan 1, 2016 at 2:34
  • what is type fswebcam or command -v fswebcam? (type the commands in the shell) Commented Jan 1, 2016 at 4:23

1 Answer 1

24

Use the subprocess module:

import subprocess
subprocess.Popen(["fswebcam", "image.jpg"])
Sign up to request clarification or add additional context in comments.

1 Comment

if os.system('fswebcam image.jpg') doesn't work (e.g., because fswebcam is an alias that is available only in the interactive shell) then subprocess.Popen(["fswebcam", "image.jpg"]) won't help either. To wait for the command to finish, use subprocess.check_call() instead Popen().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.