##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = sys.stdin和sys.argv说开去 = {{{ Eric.M sender-time Sent at 13:55 (GMT+08:00). Current time there: 8:41 PM. ✆ reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Sep 24, 2010 at 13:55 subject Re: [CPyUG] 关于sys.stdin和sys.argv的问题请教 }}} ##startInc == 缘起 == 我的一个项目一些参数需要可设定,于是做了一个web页面用来填充这些参数,填充完了之后再进行执行该脚本,返回该脚本的输出或是错误,整个工作在web上完成。 === 问题 === * 在操作的过程中遇到的问题是,如何给脚本传入数据, * 原先是写死在脚本中, 从一个指定的文件里读数据进行处理,但是不够灵活,另外脚本执行完了还有一个垃圾数据文件不优雅, * 于是想到使用stdin可以重定向来导入数据,如果单纯从stdin导入又是简单的,但是我希望做成如果stdin有数据,从stdin导入,如果没有再使用默认的从 文件中导入中, * 这时候就遇到一个问题`non-blocking stdin reading`,为了使stdin没有数据时不一直阻塞,使用了select来polling文件描述符是否有数据,在指定时间没有数据就切换到文本方式导入。 * 由于`cStringIO.StringIO`不是一个真的文件,这里就不能用它做为stdin的输入了,因为它就没有fd,因此有两种方法,一种是文件,一种是管道,我创建了一个匿名管道,来输入数据。 === 亮点 === 本项目是对http://pythonwebshell.appspot.com/interactive的一个定制版本 ,ihere同学给了指点,代码主要来自gae sdk 具体代码见此==>构建管道,重定向sys.stdin,用管道喂 * [[http://www.cnblogs.com/lexus/archive/2010/09/22/1832928.html|构建管道,重定向sys.stdin,用管道喂 - 朗志工作室(Langzhi Studio) - 博客园]] 要么是文件,要么就是管道, 因为是动态构建,就没必要产生文件了还要删除,下面是部分涉及到的代码 {{{ #!python i=int(dict["testNum"]) r="\n".join(dict["list_result"].split("\n")[:i]) fdr,fdw=os.pipe() os.write(fdw,r) os.close(fdw) f=os.fdopen(fdr) sys.stdin=f sys.stdout = results_io try: compiled_code = compile(dict["list_fetch_code"].encode("utf-8"), g.list_fetch_code_filename, 'exec') exec(compiled_code,globals()) except Exception, e: traceback.print_exc(file=results_io) except Exception,e: print e,"#############################################" finally: sys.stdout = save_stdout }}} == Shell原生判定 == {{{ Shellexy sender-time Sent at 17:52 (GMT+08:00). Current time there: 8:46 PM. ✆ reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Sep 24, 2010 at 17:52 }}} 去学习现有 Linux 程序的做法, * 当命令行参数输入文件参数为 - 时,表示从 stdin 读取。 * 或者,没输入参数时从 stdin 读取。 == 单行判别 == {{{ victor lee sender-time Sent at 19:48 (GMT+08:00). Current time there: 8:47 PM. ✆ reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Sep 24, 2010 at 19:48 }}} {{{ #!python file_=(open(arg[1]) if "-"==arg[1] else sys.stdin) if len(arg)>1 else sys.stdin }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]