如何从python中的os.system中删除0表单?

我想知道如何从
python中的os.system中删除0,例如,在这个变量中我可以删除它而没有任何问题:

user_name = check_output('whoami').strip()
output = current-user

但问题是当我运行这个变量时:

from subprocess import check_output

subtests = os.system('/home/' + user_name + '/tests/cfile --list-subtests')
output = subtests 1
         subtests 2
         0

如果我从第一个命令应用相同的命令结构,如

 subtests = check_output('/home/' + user_name + '/intel-graphics/intel-gpu-tools/tests/' + line + ' --list-subtests').strip()

它不起作用,我得到了几个python的错误,我正在研究很多,但到目前为止我找不到一个好的解决方案.

注意:我使用的是python 2.7

最佳答案 当你调用os.system时,它会启动一个新进程.该过程的标准输入和输出流连接到Python程序流.

即当你调用os.system时,无论子进程输出被写入终端(或者你的主程序输出是什么).像这样:

>>> result = os.system(".../cfile --list-subtests")
subtests 1
subtests 2
>>> result
0

上面的“子测试1”/“子测试2”行只是从子进程传递到终端的文本.它从未被Python处理或转到任何变量.返回值仅为0,这通常意味着操作已成功完成.

如果你想捕获输出使用the subprocess module,check_output(就像你在第一个例子中使用的那样!)或泛型Popen:

>>> process = subprocess.Popen([".../cfile", "--list-subtests"], stdout=subprocess.PIPE)
>>> process_out, process_err = process.communicate()
>>> process_out
'subtests 1\nsubtests 2\n'
>>> process.returncode
0
点赞