python子进程输出到列表或文件 [英] python subprocess output to list or file
问题描述
我想在 Python 3 中运行以下 bash 命令:
I want to run the following bash command in Python 3:
ls -l
我知道我可以做到以下几点:
I know that I can do the following:
from subprocess import call
call(['ls', '-l'])
如何将此输出保存到文件中,或将其放入列表或集合中?
How do I save this output to a file, or put it into lists or sets?
[-rw-r--r--] [1] [name] [staff] [426] [14 Jan 21:52] [HelloWorld.class]
[-rw-r--r--@] [1] [name] [staff] [107] [14 Jan 21:51] [HelloWorld.java]
...
etc.
我希望能够直接访问特定信息,然后将其添加到集合中,但我不知道将列出多少项.
I want to be able to access particular information directly, and then add it to the set, but I do not know how many items will be listed.
任何提示、片段或示例都会有所帮助.
Any hints, snippets, or examples would really help.
推荐答案
访问 ls -l
输出中的信息的一种方法是解析它.例如,csv.DictReader
可用于将每一列映射到字典中的一个字段:
One way to access to the information in ls -l
output is to parse it. For example, csv.DictReader
could be use to map each column to a field in a dictionary:
import subprocess
import csv
process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
reader = csv.DictReader(stdout.decode('ascii').splitlines(),
delimiter=' ', skipinitialspace=True,
fieldnames=['permissions', 'links',
'owner', 'group', 'size',
'date', 'time', 'name'])
for row in reader:
print(row)
上面的代码将在 ls -l
输出中为每一行打印一个字典,例如:
The code above will print a dictionary for each line in ls -l
output such as:
{'group': '<group_name>',
'name': '<filename>',
'links': '1',
'date': '<modified_date>',
'time': '<modified_time>',
'owner': '<user_name>',
'permissions': '-rw-rw-r--',
'size': '<size>'}
这篇关于python子进程输出到列表或文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!