How do I run a command line command in a Python script?

  • I'm using 2 separate scripts, and To run them I enter sudo python or sudo python from the terminal command line. I would like to have a line in the script in which if I press a button, the program breaks and runs Something like this, which doesn't work.

    if GPIO.input(23) == False:
        break(sudo python
  • mrwhale

    mrwhale Correct answer

    6 years ago

    os.system("sudo python")

    first you will need to import the os module

    import os

    I don't have a pi with me atm to test, but this comes from the second answer to this question:

    This is what I tried and it worked, thanks a lot Harry! But I did have to combine both programs first. Now the os.system("sudo python") simply restarts at the beginning of program, which is fine. I think import will also work. I didn't try subprocess, it does look interesting and is probably something I need to learn.

    `os.system()` has been depricated in favor of `subprocess`, see

  • In general, use the subprocess module["sudo","python",""]) 

    for command line calls.

    An example processing the result of a subprocess call;

     result = subprocess.check_output(['sudo','service','mpd','restart'])

    Subprocess replaces several older modules and functions, like os.system and os.spawn. It does a good job in sanitizing arguments, so it protects you from shell injection.

    Of course to run a second python script there is no need for CLI call, you can import those.

    I'm trying to learn how to issue commands from within a Python script (see here and here) and having some problems. I wonder if `subprocess` might be better in my case as well.

  • You can use sudo as harry sib suggested, but you would have to add the user running the first script to the sudoers file.

    The best way to run a python script from another python script is to import it. You should have the logic of your script in a method in the second script:

    def run():
    # Run it only if called from the command line
    if __name__ == '__main__':
    import Scale2
    if (GPIO.input(23) == False):

    +1, Since python is capable of this, it will be the `cleanest` answer.

    +1, this is the correct way to do what the OP wants and should probably be the accepted answer.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM