如何从Python启动命令行命令

11

我有一系列的命令,是从命令行中调用特定的工具程序。具体而言:

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

我似乎无法弄清楚(或找到明确的文档)如何编写Python脚本来发送这些命令。我之前没有使用过os模块,但怀疑也许那就是我应该寻找的地方?

2个回答

3

使用子进程(subprocess),可以方便地执行命令行命令并获取输出或检查是否发生了错误:

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

示例:

print external_command('ls -l')

重新排列返回值应该没有问题。

1
使用 subprocess
示例:
>>> subprocess.call(["ls", "-l"])
0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接