Differences between revisions 1 and 2
Revision 1 as of 2010-09-24 12:49:12
Size: 3656
Editor: ZoomQuiet
Comment:
Revision 2 as of 2010-09-24 13:07:09
Size: 3657
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 18: Line 18:
}} }}}

sys.stdin和sys.argv说开去

Eric.M <[email protected]>
sender-time     Sent at 13:55 (GMT+08:00). Current time there: 8:41 PM. ✆
reply-to        [email protected]
to      [email protected]
date    Fri, Sep 24, 2010 at 13:55
subject Re: [CPyUG] 关于sys.stdin和sys.argv的问题请教

缘起

  • 我的一个项目一些参数需要可设定,于是做了一个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,用管道喂

要么是文件,要么就是管道, 因为是动态构建,就没必要产生文件了还要删除,下面是部分涉及到的代码

   1 i=int(dict["testNum"])
   2 r="\n".join(dict["list_result"].split("\n")[:i])
   3 fdr,fdw=os.pipe()
   4 os.write(fdw,r)
   5 os.close(fdw)
   6 f=os.fdopen(fdr)
   7 sys.stdin=f
   8 sys.stdout  = results_io
   9 
  10 try:
  11     compiled_code = compile(dict["list_fetch_code"].encode("utf-8"), g.list_fetch_code_filename, 'exec')
  12     exec(compiled_code,globals())
  13 except Exception, e:
  14         traceback.print_exc(file=results_io)
  15 
  16 except Exception,e:
  17     print e,"#############################################"
  18 finally:
  19     sys.stdout = save_stdout

Shell原生判定

Shellexy <[email protected]>
sender-time     Sent at 17:52 (GMT+08:00). Current time there: 8:46 PM. ✆
reply-to        [email protected]
to      [email protected]
date    Fri, Sep 24, 2010 at 17:52

去学习现有 Linux 程序的做法,

  • 当命令行参数输入文件参数为 - 时,表示从 stdin 读取。
  • 或者,没输入参数时从 stdin 读取。

单行判别

victor lee <[email protected]>
sender-time     Sent at 19:48 (GMT+08:00). Current time there: 8:47 PM. ✆
reply-to        [email protected]
to      [email protected]
date    Fri, Sep 24, 2010 at 19:48

   1 file_=(open(arg[1]) if "-"==arg[1] else sys.stdin) if len(arg)>1 else sys.stdin


反馈

创建 by -- ZoomQuiet [2010-09-24 12:49:12]

MiscItems/2010-09-23 (last edited 2010-09-24 13:07:09 by ZoomQuiet)