43

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?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
BrandonMayU
  • 726
  • 2
  • 6
  • 13
  • 5
    Please show some actual code you've tried and the error you got. – Daniel Roseman Jan 01 '16 at 00:24
  • 9
    is this what you want? http://stackoverflow.com/questions/89228/calling-an-external-command-in-python – Jezzamon Jan 01 '16 at 00:42
  • 1
    @KevinGuan Probably. However the `subprocess` module is preferred. – cdonts Jan 01 '16 at 00: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_. – Sergey Salnikov Jan 01 '16 at 02:34
  • what is `type fswebcam` or `command -v fswebcam`? (type the commands in the shell) – jfs Jan 01 '16 at 04:23

1 Answers1

24

Use the subprocess module:

import subprocess
subprocess.Popen(["fswebcam", "image.jpg"])
vesche
  • 1,842
  • 1
  • 13
  • 19
  • 2
    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()`. – jfs Jan 01 '16 at 04:20