2014-08-28 3 views
2

파이썬 문을 포함하고있는 파일이 있는데, 파이썬을 실행하여 명령이 REPL에서 실행 된 경우 표시 될 내용을 stdout에 인쇄합니다.파이썬 REPL에 파이핑 명령

예를 들어, 파일이

1 + 4 
'a' + 'b' 

그런 다음 출력이

>>> 1 + 4 
5 
>>> 'a' + 'b' 
'ab' 

이 할 수있는 방법이 있나요해야하는 경우?

+1

Windows? * n * x? 크로스 플랫폼? –

+0

리눅스, 크로스 플랫폼 접근 방식이 정말 좋겠지 만. –

답변

3

당신은이 목표를 달성하기 위해 pexpect에서 replwrap을 사용할 수 있습니다 심지어 python 방법이있다 pexpect의 최신 버전을 구하십시오.

2

일부 AST 마법은 여기에 도움이 될 수 있습니다

import ast 
import itertools 


def main(): 
    with open('test.txt', 'r') as sr: 
     parsed = ast.parse(sr.read()) 
     sr.seek(0) 
     globals_ = {} 
     locals_ = {} 
     prev_lineno = 0 
     for node in ast.iter_child_nodes(parsed): 
      source = '\n'.join(itertools.islice(sr, 0, node.lineno - prev_lineno))[:-1] 
      print('>>> {}'.format(source)) 
      if isinstance(node, ast.Expr): 
       print(eval(source, globals_, locals_)) 
      else: 
       exec(source, globals_, locals_) 
      prev_lineno = node.lineno 

if __name__ == '__main__': 
    main() 

입력 :

1 + 4 
'a' + 'b' 
a = 1 
a 

출력 :

이 각각의 시작과 끝 라인 번호를 찾을 수 있습니다 무엇을
>>> 1 + 4 
5 
>>> 'a' + 'b' 
ab 
>>> a = 1 
>>> a 
1 

ast 모듈을 사용하여 소스를 구문 분석 한 다음 eval 또는 exec 인 경우 명령문인지 표현식인지에 따라 다릅니다.

컨텍스트는 globals_locals_에 저장됩니다.

파이썬 샌드 박스를 사용하여 evalexec을 수행하면 더 안전하게 만들 수 있습니다.

3
신속하고 code 모듈을 사용하여 (주로) 더러운

(그리) : 개선의 여지의

import sys 
import code 

infile = open('cmd.py') 
def readcmd(prompt): 
    line = infile.readline() 
    if not line: 
     sys.exit(0) 

    print prompt,line.rstrip() 
    return line.rstrip() 

code.interact(readfunc=readcmd) 

많은,하지만 늦었 여기. 어쨌든, 예 :

from pexpect import replwrap 

with open("commands.txt", "r") as f: 
    commands = [command.strip() for command in f.readlines()] 

repl = replwrap.python() 
for command in commands: 
    print ">>>", command 
    print repl.run_command(command), 

반환 :

python replgo.py 
>>> 1 + 4 
5 
>>> 'a' + 'b' 
'ab' 
당신은해야합니다

sh$ cat cmd.py 
1 + 4 
'a' + 'b' 

1/0 

def f(x): 
    return x*2 

f(3) 
sh$ python console.py 
Python 2.7.3 (default, Mar 13 2014, 11:03:55) 
[GCC 4.7.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 
>>> 1 + 4 
5 
>>> 'a' + 'b' 
'ab' 
>>> 
>>> 1/0 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
ZeroDivisionError: integer division or modulo by zero 
>>> 
>>> def f(x): 
...  return x*2 
... 
>>> f(3) 
6 
0

입력을 파이썬 "코드"모듈로 파이프 할 수 있습니다. 출력은 표시되지만 입력은 표시되지 않습니다.

$ echo '1 + 1' | python -m code 
Python 2.7.10 (v2.7.10:15c95b7d81dc, May 23 2015, 09:33:12) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 
>>> 2 
관련 문제