Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a command line command from Python [duplicate]

I've got a series of commands I'm making from the command line where I call certain utilities. Specifically:

root@beaglebone:~# canconfig can0 bitrate 50000 ctrlmode triple-sampling on loopback on
root@beaglebone:~# cansend can0 -i 0x10 0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88
root@beaglebone:~# cansequence can0 -p

I can't seem to figure out (or find clear documentation on) how exactly I write a Python script to send these commands. I haven't used the os module before, but suspect maybe that's where I should be looking?

like image 902
Chris Avatar asked Feb 19 '13 14:02

Chris


People also ask

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

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do you repeat a command in Python shell?

Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press "enter", that command will be repeated at the current command prompt. Press enter again, and the command gets executed.

Can you run command prompt commands in Python?

Methods to Execute a Command Prompt Command from Python Now what if you want to execute multiple command prompt commands from Python? If that's the case, you can insert the '&' symbol (or other symbols, such as '&&' for instance) in between the commands.


2 Answers

With subprocess one can conveniently perform command-line commands and retrieve the output or whether an error occurred:

import subprocess
def external_command(cmd): 
    process = subprocess.Popen(cmd.split(' '),
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

    # wait for the process to terminate
    out, err = process.communicate()
    errcode = process.returncode

    return errcode, out, err

Example:

print external_command('ls -l')

It should be no problem to rearrange the return values.

like image 87
Alex Avatar answered Oct 12 '22 15:10

Alex


Use subprocess.

Example:

>>> subprocess.call(["ls", "-l"])
0

>>> subprocess.call("exit 1", shell=True)
1
like image 36
Fredrik Pihl Avatar answered Oct 12 '22 14:10

Fredrik Pihl