我无法理解如何使用subprocess
解决我的问题。如何使用子进程和'cat'逐行读入数据?
假设我在我的子目录中有一个制表符分隔的文本文件tabdelimited1.txt
,我想读入熊猫数据框。
当然,你可以简单地导入数据如下:
import pandas as pd
df = pd.read_csv("tabdelimited1.txt", header=None, sep="\s+")
然而,假设我们想用subprocess
。在命令行中,$cat tabdelimited1.txt
将输出所有行。
现在,我想使用子进程读取cat tabdelimited1.txt
的输出。如何做到这一点?
我们可以使用
import subprocess
task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE)
data = task.stdout.read()
,但(1)我得到shell=True
和(2)我想在数据线,由线到读取错误。
如何使用subprocess
逐行读取tabdelimited1.txt
?这个脚本应该是这个样子:
import subprocess
import pandas as pd
df = pd.DataFrame()
task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE)
# while lines exist:
# line = subprocess std
df=pd.concat([df, line])
EDITED
你用'shell = True'得到了什么错误? – tdelaney
子进程模块与从管道输入读取无关,你只需要[从sys.stdin读取](http://stackoverflow.com/questions/17658512/how-to-pipe-input-to-python -linux-program-in-line-from-line-from-linux-program)for cat x.txt | python script1.py'。 – TessellatingHeckler
@TessellatingHeckler但是OP想要使用'subprocess'。 – tdelaney