简体   繁体   English

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

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

I am writing a script to sort a file based on a specific column. 我正在编写一个脚本,用于根据特定列对文件进行排序。 I tried calling the 'sort' Linux command for this. 我尝试为此调用“ sort” Linux命令。 The code I am using is: 我使用的代码是:

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)

But this doesn't work properly. 但这不能正常工作。 Thanks in advance for helping. 在此先感谢您的帮助。

Use communicate to get the output: 使用communication获取输出:

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

Or just use check_output for python >= 2.7: 或者仅将check_output用于python> = 2.7:

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

If you want to just write the sorted contents you can redirect stdout to a file object: 如果您只想编写排序的内容,则可以将stdout重定向到文件对象:

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

First of all, I hope that output and new_path are actually strings (I assume so, but it's not clear from what you posted). 首先,我希望outputnew_path实际上是字符串(我假设是这样,但是您发布的内容尚不清楚)。 But assuming all of that is sorted out: 但是,假设所有这些都已解决:

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

That should store the contents of the subprocess's standard output to sorting_output . 那应该将子流程的标准输出的内容存储到sorting_output

To emulate the shell command: 模拟shell命令:

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

ie, to sort /homes/varshith/maf file by the 2nd column and to store the sorted output to /homes/varshith/maf_sort.bed file in Python: 即,按第二列对/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)

It overwrites the output file. 它将覆盖输出文件。 To append to the file instead, use ab mode instead of wb . 要附加到文件,请使用ab模式代替wb

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

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