从python运行bash命令并捕获文件对象

时间:2018-03-16 00:08:14

标签: python linux jupyter-notebook

在jupyter笔记本中我可以运行以下命令并获取一个文件对象列表,然后我可以打开它:

PATH = someuser/data
files = get_ipython().getoutput('ls {PATH}') #%ls {PATH} in notebook
#then I can run
text = get_ipython().getoutput('less {PATH}{files[0]}')
print(text)

我尝试了以下内容:

path = f"{PATH}"
files = subprocess.call(['ls', path])

files = subprocess.run(['ls', path], stdout=subprocess.PIPE).stdout.decode('utf-8')

files = os.system(path)

但我只能得到一个字符串对象而不是文件对象,然后我可以打开它并从中获取数据。

1 个答案:

答案 0 :(得分:2)

文件名字符串。这是您传递给open以获取文件对象的内容,然后您可以从中获取数据。例如,假设您有一个名为spam.py的脚本:

filename = 'spam.py'
with open(filename) as fileobj:
    data = fileobj.read()
print(data)

当你运行它时,它会打印出来。

现在,您在subprocess.run上调用ls并读取其stdout时返回的输出不是每个文件的字符串,而是一个大字符串。

这里简单的答案就是不要呼唤ls。 Python已经可以为您获取文件名列表:

filenames = os.listdir(path)
for filename in filenames:
    with open(filename) as fileobj:
        # do stuff with fileobj

但如果你真的必须,你可以使用例如splitlines方法将你拥有的输出变成一个行列表,这与listdir返回的内容非常相似,只是以更复杂的方式检索。

相关问题