为什么Python3无法执行某些Linux命令?

4

我可以在树莓派3终端上运行mjpg-streamer。

以下是我使用的命令。

mjpg_streamer -i "input_uvc.so -d /dev/video0 -r 800x448" -o "output_http.so -p 8090 -w /usr/local/share/mjpg-streamer/www/"

我现在想在Python 3上执行它。所以我尝试使用os.system()和subprocess.call(),但是它无法执行,并且在运行代码后网络摄像头出了问题,因此我不得不重新启动树莓派3。即使os.system()的代码如os.system('python3 test.py')一样也可以正常工作。

不可能使用Python 3代码执行mjpg-streamer吗?

以下是我的代码。

import os

os.system('mjpg_streamer -i "input_uvc.so -d /dev/video0 -r 800x448" -o "output_http.so -p 8090 -w /usr/local/share/mjpg-streamer/www/"')
1个回答

4

你可以尝试使用subprocess,它允许保存标准输出和错误输出:

    import subprocess
    ### define the command
    command = 'mjpg_streamer -i "input_uvc.so -d /dev/video0 -r 800x448" -o "output_http.so -p 8090 -w /usr/local/share/mjpg-streamer/www/"'
    ### execute the command and save stdout and stderr as variables
    output, error = subprocess.Popen(command, universal_newlines=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

您将会把标准输出保存在"output"变量中,而"stderr"则保存在"error"变量中。

顺带一提:建议使用所列格式


非常感谢!!它起作用了!!我可以问一下如何在执行后停止它吗?我使用另一个变量来执行'killall mjpg_streamer',但我认为有一些函数可以停止subprocess.Popen.communicate()。 - allentando
2
你可以根据进程ID终止正在执行的进程,例如: proc = subprocess.Popen(command, universal_newlines=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 将其获取并像以前一样执行:output,error = proc.communicate() 然后根据ID停止进程(需要导入 ossignal): os.killpg(os.getpgid(proc.pid), signal.SIGTERM) - cccnrc
非常感谢!这真的帮了我很多。 - allentando

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