如何从python中提供命令行命令? [重复]

时间:2021-10-18 00:06:46

This question already has an answer here:

这个问题在这里已有答案:

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

What I can't seem to figure out (or find clear documentation on) is 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 at?

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

2 个解决方案

#1


1  

Use subprocess

example:

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

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

#2


1  

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.

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

#1


1  

Use subprocess

example:

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

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

#2


1  

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.

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