bash 使用 Python 列出的命令输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24823815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Output of command to list using Python
提问by Swaroop Kundeti
I'm writing an automation script, where it needs to run a command and the output of command should be captured as a list.
我正在编写一个自动化脚本,它需要运行一个命令,并且命令的输出应该被捕获为一个列表。
For example:
例如:
# ls -l | awk '{print }' test1 test2
I want the output to be captured as a list like var = ["test1", "test2"]
.
我希望输出被捕获为一个列表,如var = ["test1", "test2"]
.
Right now I tried this but it is saving as string instead of list:
现在我试过这个,但它保存为字符串而不是列表:
# Filter the tungsten services s = subprocess.Popen(["ls -l | awk '{print }'"], shell=True, stdout=subprocess.PIPE).stdout service_state = s.read()
Please guide me if anyone has any idea to achieve this.
如果有人有任何想法来实现这一目标,请指导我。
采纳答案by Aaron Digulla
You can use
您可以使用
service_states = s.read().splitlines()
but note that this is brittle: File names can contain odd characters (like spaces).
但请注意,这很脆弱:文件名可以包含奇数字符(如空格)。
So you're probably better off using os.listdir(path)
which gives you a list of file names.
所以你最好使用os.listdir(path)
它给你一个文件名列表。
回答by Juan Diego Godoy Robles
No needed for subprocess:
不需要子流程:
a, d , c = os.walk('.').next()
service_state = d + c
回答by OBu
You can post-process the string according to your needs.
您可以根据需要对字符串进行后处理。
string.splitlines()
(https://docs.python.org/2/library/stdtypes.html#str.splitlines) will break the string into a list of lines.
string.splitlines()
( https://docs.python.org/2/library/stdtypes.html#str.splitlines) 将字符串分解为行列表。
If you need to split the results further, you can use .split()
.
如果需要进一步拆分结果,可以使用.split()
.