社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何从python脚本运行终端命令,并将输出保存到。csv文件?[重复]

MunSka 2002 • 3 年前 • 1226 次点击  

有没有一种方法可以将子流程的输出转化为可编辑的csv。读卡器或csv。听写器对象?以下是我一直在尝试的代码:

p2 = subprocess.Popen("sort command...", stdout=subprocess.PIPE)
output = p2.communicate()[0]
edits = csv.reader(output, delimiter="\t")

基本上,我会对一个大的CSV文件进行排序,然后我想把它作为CSV文件放到Python中。读卡器对象。

我得到的错误是

错误:迭代器应该返回字符串,而不是int(您是在文本模式下打开文件的吗?)

有没有办法将此ByTestStream视为csv。读者反对,还是我的想法不对?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131776
 
1226 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Weylin Piegorsch
Reply   •   1 楼
Weylin Piegorsch    3 年前

如果您的CSV文件有列标题,则此选项有效。

[ user@system currentDir ]$ ./ProgramThatCreatesCSVData
first,second,third,fourth
1,2,3,4
9,10,11,12
a,b,c,d
5,6,7,8
[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$ cat CSVtoDict.py
#!/usr/bin/python3
"""Sample program to open a pipe to run a command.
That command generates a CSV with heading names in the first row.
Output of this program is a conversion of that CSV to a list of dictionaries,
in pprint format."""

import csv, pprint, subprocess, io

pipe = subprocess.Popen(["./ProgramThatCreatesCSVData"], stdout=subprocess.PIPE)
pipeWrapper = io.TextIOWrapper(pipe.stdout)
pipeReader = csv.DictReader(pipeWrapper)
listOfDicts = [ dict(row) for row in pipeReader ]

pprint.pprint(listOfDicts)

[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$ python3 CSVtoDict.py
[{'first': '1', 'fourth': '4', 'second': '2', 'third': '3'},
 {'first': '9', 'fourth': '12', 'second': '10', 'third': '11'},
 {'first': 'a', 'fourth': 'd', 'second': 'b', 'third': 'c'},
 {'first': '5', 'fourth': '8', 'second': '6', 'third': '7'}]
[ user@system currentDir ]$
jfs
Reply   •   2 楼
jfs    10 年前

要启用文本模式,请通过 universal_newlines=True 参数:

#!/usr/bin/env python3
import csv
from subprocess import Popen, PIPE

with Popen(["sort", "a.csv"], stdout=PIPE, universal_newlines=True) as p:
    print(list(csv.reader(p.stdout, delimiter="\t")))

如果需要解释引号字段中嵌入的换行符,请创建 io.TextIOWrapper ,通过 newline='' 参数:

#!/usr/bin/env python3
import csv
import io
from subprocess import Popen, PIPE

with Popen(["sort", "a.csv"], stdout=PIPE) as p, \
     io.TextIOWrapper(p.stdout, newline='') as text_file:
    print(list(csv.reader(text_file, delimiter="\t")))

而且 TextIOWrapper 允许显式指定字符编码(否则为默认值) locale.getpreferredencoding(False) (已使用)。

注意:您不需要外部 sort 命令可以用纯Python对行进行排序:

#!/usr/bin/env python3
import csv

with open('a.csv', newline='') as text_file:
    rows = list(csv.reader(text_file, delimiter="\t"))
    rows.sort()
    print(rows)

注意:更高版本对csv行而不是物理行进行排序(如果需要,可以对行进行排序)。

martineau
Reply   •   3 楼
martineau    10 年前

以下内容对我很有用(尽管医生警告我不要从 stdout ).包装 斯特杜特 带着 io.TextIOWrapper() 支持字段数据中嵌入的换行符。

这样做可以使用发电机,其优点是 斯特杜特 一次读一行。

p2 = subprocess.Popen(["sort", "tabbed.csv"], stdout=subprocess.PIPE)
output = io.TextIOWrapper(p2.stdout, newline=os.linesep)
edits = csv.reader((line for line in output), delimiter="\t")
for row in edits:
    print(row)

输出:

['1', '2', '3', '4']
['5', '6', '7', '8']
['9', '10', '11', '12']
['a', 'b\r\nx', 'c', 'd']

这个 tabbed.csv 输入测试文件包含以下内容(其中 » 表示制表符和 ≡ 换行符):

1»2»3»4
9»10»11»12
a»"b≡x"»c»d
5»6»7»8
mhawke
Reply   •   4 楼
mhawke    10 年前

这是Python 3中的一个问题。CSV模块需要unicode输入,而不是字节字符串。除此之外, csv.reader() 需要一个iterable,例如打开的文件或字符串列表。试试这个:

encoding = 'ascii'    # specify the encoding of the CSV data
p2 = subprocess.Popen(['sort', '/tmp/data.csv'], stdout=subprocess.PIPE)
output = p2.communicate()[0].decode(encoding)
edits = csv.reader(output.splitlines(), delimiter=",")
for row in edits:
    print(row)

如果 /tmp/data.csv 包含(我使用逗号作为分隔符):

1,2,3,4
9,10,11,12
a,b,c,d
5,6,7,8

那么,输出将是:

['1', '2', '3', '4']
['5', '6', '7', '8']
['9', '10', '11', '12']
['a', 'b', 'c', 'd']