简体   繁体   中英

Python: subprocess.check_output()

I am trying to retreive a list of CPU features, for a configure.py script I'm writing. In the shell, I do as follows:

$ 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

My naive attempt is to write:

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

But I get some errors:

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

you have to provide a list of string or a tuples of string for distinc arguments. Also the pipes are not program arguments.

see this post to understand how pipes are done: Python subprocess command with pipe

A better option would be to use:

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

Also using spaces before and after '|' improve readability. Note also that grep flags /proc/cpuinfo is equivalent to cat /proc/cpuinfo | grep flags cat /proc/cpuinfo | grep flags .

EDIT

As mentioned os.popen is deprecated, use this instead:

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

If you want this to work please add:

shell=True

The error you're getting is because it's trying to find it inside python instead of the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM