简体   繁体   English

Python:subprocess.check_output()

[英]Python: subprocess.check_output()

I am trying to retreive a list of CPU features, for a configure.py script I'm writing.我正在尝试为我正在编写的 configure.py 脚本检索 CPU 功能列表。 In the shell, I do as follows:在 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

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. 您必须为distinc参数提供一个字符串列表或一个字符串元组。 Also the pipes are not program arguments. 此外,管道也不是程序参数。

see this post to understand how pipes are done: Python subprocess command with pipe 请参阅这篇文章以了解如何完成管道: 带管道的Python子进程命令

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 还要注意, grep flags /proc/cpuinfo等同于cat /proc/cpuinfo | grep flags cat /proc/cpuinfo | grep flags . cat /proc/cpuinfo | grep flags

EDIT 编辑

As mentioned os.popen is deprecated, use this instead: 如前所述,不建议使用os.popen ,而应使用以下命令:

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.您遇到的错误是因为它试图在 python 而不是 shell 中找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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