How to pass command line command from python?

I have a number of commands that I do from the command line where I call some utilities. In particular:

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

      

What I cannot understand (or find clear documentation) is exactly how I write a python script to send these commands. I haven't used the os module before, but I suspect maybe where should I look?

+3


source to share


2 answers


Use subprocess

Example:



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

>>> subprocess.call("exit 1", shell=True)
1

      

+1


source


It is convenient to execute command line commands with a subprocess and retrieve the result or 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')

      

No need to rearrange the return values.

+1


source







All Articles