繁体   English   中英

如何在Python中存储Linux调用的输出

[英]How to store output from linux call in Python

我正在编写一个脚本,用于根据特定列对文件进行排序。 我尝试为此调用“ sort” Linux命令。 我使用的代码是:

from subprocess import 
path_store = /homes/varshith/maf
input = path_store
field = "-k2"
store_output_in_new_file = ">"
new_path = path_store + "_sort.bed"
sorting = Popen(["sort", field, input, append, new_path], stdout=PIPE)

但这不能正常工作。 在此先感谢您的帮助。

使用communication获取输出:

from subprocess import PIPE,Popen
sorting = Popen(["sort", field, output, append, new_path], stdout=PIPE)
out, err = sorting.communicate()  
print out

或者仅将check_output用于python> = 2.7:

sorting = check_output(["sort", field, output, append, new_path])

如果您只想编写排序的内容,则可以将stdout重定向到文件对象:

output = "path/to/parentfile"
cmd = "sort -k2 {}".format(output)
with open(new_file,"w") as f:
    sorting = Popen(cmd.split(),stdout=f)

首先,我希望outputnew_path实际上是字符串(我假设是这样,但是您发布的内容尚不清楚)。 但是,假设所有这些都已解决:

sorting = Popen(...)
sorting_output = sorting.communicate()[0]

那应该将子流程的标准输出的内容存储到sorting_output

模拟shell命令:

$ sort -k2  /homes/varshith/maf > /homes/varshith/maf_sort.bed

即,按第二列对/homes/varshith/maf文件进行排序,并将排序后的输出存储到Python中的/homes/varshith/maf_sort.bed文件中:

#!/usr/bin/env python
from subprocess import check_call

field = '-k2'
input_path  = '/homes/varshith/maf'
output_path = input_path + '_sort.bed'
with open(output_path, 'wb', 0) as output_file:
    check_call(["sort", field, input_path], stdout=output_file)

它将覆盖输出文件。 要附加到文件,请使用ab模式代替wb

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM