IPython:如何将内容输入Python脚本 [英] IPython: how do I pipe something into a Python script

查看:156
本文介绍了IPython:如何将内容输入Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过运行test.py 在IPython中运行脚本并从那里进行调试。

I understand I can run a script in IPython via run test.py and debug from there.

但是如何将输出传输到test.py?例如,通常我可以在命令行中运行,如 grepABCinput.txt | ./test.py ,但我如何在IPython中做同样的事情?

But how do I pipe an output into test.py? For example, normally I could run in the command line like grep "ABC" input.txt | ./test.py, but how do I do the same thing in IPython?

谢谢!

推荐答案

在Python脚本中你应该从sys.stdin中读取:

Inside the Python script you should be reading from sys.stdin:

import sys

INPUT = sys.stdin

def do_something_with_data(line):
    # Do your magic here
    ...
    return result

def main():
    for line in INPUT:
        print 'Result:', do_something_with_data(line)

if __name__ == '__main__':
    main()

在迭代解释器中,您可以使用子进程模块模拟sys.stdin。

Inside the iterative interpreter you can use the subprocess module mock sys.stdin.

In[0]: from test.py import *
In[1]: INPUT = subprocess.Popen(['grep', 'ABC', 'input.txt'], \
                               stdout=subprocess.PIPE).stdout
In[2]: main()

您还可以将输出传输到文件,只需从文件中读取即可。出于实际目的,stdin只是另一个文件。

You can also pipe the output to a file and just read from the file. For practical purposes stdin is just another file.

In[0]: ! grep "ABC" input.txt > output.txt
In[1]: INPUT = open('output.txt')
In[2]: main()

这篇关于IPython:如何将内容输入Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆