Python:subprocess.check_output()

时间:2014-12-04 11:26:42

标签: python

我正在尝试检索一系列CPU功能,对于我正在编写的configure.py脚本。在shell中,我做如下:

$ cat /proc/cpuinfo|grep flags|head -1|cut -d\: -f2
 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms

我天真的尝试是写:

features = subprocess.check_output("cat /proc/cpuinfo|grep flags|head -1|cut -d\: -f2").split()

但我收到了一些错误:

File "./configure.py", line 14, in <module>
  features = subprocess.check_output("cat /proc/cpuinfo|grep flags|head -1|cut -d\: -f2").split()
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
  process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
  errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child
  raise child_exception
OSError: [Errno 2] No such file or directory

1 个答案:

答案 0 :(得分:4)

你必须为distinc参数提供字符串列表或字符串元组。管道也不是程序参数。

请参阅此帖子以了解管道是如何完成的: Python subprocess command with pipe

更好的选择是使用:

os.popen("cat /proc/cpuinfo | grep flags | head -1 | cut -d\: -f2").read().split()

在'|'之前和之后也使用空格提高可读性。另请注意,grep flags /proc/cpuinfo相当于cat /proc/cpuinfo | grep flags

修改

如上所述os.popen已弃用,请改用:

subprocess.check_output("cat /proc/cpuinfo | grep flags | head -1 | cut -d\: -f2", shell=True).split()