Execute terminal commands in python3

14,382

Use the subprocess module:

import subprocess
subprocess.Popen(["fswebcam", "image.jpg"])
Share:
14,382
BrandonMayU
Author by

BrandonMayU

Updated on June 05, 2022

Comments

  • BrandonMayU
    BrandonMayU almost 2 years

    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
    jfs over 8 years
    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().