Created
October 29, 2010 15:06
-
-
Save aolshevskiy/653713 to your computer and use it in GitHub Desktop.
RJyC doc sources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cmd import Cmd as BaseCmd | |
from code import InteractiveConsole as BaseInteractiveConsole | |
import re, sys | |
from xmlrpclib import ServerProxy | |
class Cmd(BaseCmd): | |
"""Реализация прокси-консоли""" | |
reg = re.compile('^\s*') | |
def __init__(self, host, port): | |
BaseCmd.__init__(self) | |
self.s = ServerProxy('http://%s:%d' % (host, int(port))) #Клиент нашего сервиса | |
self.prompt = '>>> ' #Приглашение к вводу | |
self.leading_ws = '' #Переменная для ведущих пробелов | |
self.is_empty = False #Переменная определяющая пустую команду | |
def precmd(self, line): | |
"""Тестируем различные условия с сырой строкой, | |
которая затем фильтруется""" | |
self.leading_ws = self.reg.match(line).group(0) #Сохраняем ведущие пробелы, т.к. они фильтруется при передаче в default | |
self.is_empty = (line == '') #Пустая ли команда, т.к. пустая команда далее преобразуется в повторение предыдущей | |
return line #Выполняем контракт, описанный в документации | |
def default(self, line): | |
if(self.is_empty): #Восстанавливаем пустую строкy | |
line = '' | |
line = self.leading_ws + line #Восстанавливаем ведущие пробелы | |
(result, output) = self.s.push(line) #Выполняем строку в удалённой консоли | |
self.prompt = ('... ' if result else '>>> ') #В случае если требуется новый ввод устанавливаем соответствующее приглашение | |
sys.stdout.write(output) #Пишем аутпут в аутпут :) | |
if __name__ == '__main__': | |
HOST, PORT = sys.argv[1:] | |
Cmd(HOST, PORT).cmdloop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.servlet.http.*; | |
import java.util.*; | |
import java.io.*; | |
import net.rjyc.Server; | |
public class Hello extends HttpServlet { | |
public final Map<String, String> links = new HashMap<String, String>(); | |
{ | |
links.put("Python", "http://python.org"); | |
links.put("Java", "http://java.net"); | |
Thread t = new Thread() { | |
@Override public void run() { | |
Map<String, Object> locals = new HashMap<String, Object>(); | |
locals.put("this", Hello.this); | |
new Server("localhost", 8081, locals).start(); | |
} | |
}; | |
t.start(); | |
} | |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) | |
throws IOException { | |
PrintWriter writer = response.getWriter(); | |
for(Map.Entry<String, String> e: links.entrySet()) | |
writer.println("<a href=\""+e.getValue()+"\">"+e.getKey()+"</a>"); | |
writer.close(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.servlet.http.*; | |
import java.util.*; | |
import java.io.*; | |
public class Hello extends HttpServlet { | |
public final Map<String, String> links = new HashMap<String, String>(); | |
{ | |
links.put("Python", "http://python.org"); | |
links.put("Java", "http://java.net"); | |
} | |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) | |
throws IOException { | |
PrintWriter writer = response.getWriter(); | |
for(Map.Entry<String, String> e: links.entrySet()) | |
writer.println("<a href=\""+e.getValue()+"\">"+e.getKey()+"</a>"); | |
writer.close(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.rjyc; | |
import org.python.util.PythonInterpreter; | |
import java.util.*; | |
public class Server { | |
private PythonInterpreter i; | |
public PythonInterpreter getInterpreter() { | |
return i; | |
} | |
public Server(String host, int port) { | |
this(host, port, new HashMap<String, Object>()); | |
} | |
public Server(String host, int port, Map<String, Object> locals) { | |
i = new PythonInterpreter(); | |
//устанавливаем аргументы в экземпляр интерпретатора | |
i.set("host", host); | |
i.set("port", port); | |
i.set("ls", locals); | |
} | |
public void start() { | |
//запускаем сервер интерактивной консоли | |
i.exec("from rjyc import Server; Server(dict(ls), (host, port), logRequests = False).serve_forever()"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from SimpleXMLRPCServer import * | |
from os import path | |
from code import InteractiveConsole as BaseInteractiveConsole | |
class Stdout(object): | |
"""Замена stdout для буферизации вывода в строку""" | |
def __init__(self): | |
self.buffer = '' | |
def get_buffer(self): | |
"""Получаем накопленный буфер и сбрасываем его""" | |
bc = self.buffer | |
self.buffer = '' | |
return bc | |
def write(self, bs): | |
"""Пишем в буфер вместо стандартного вывода""" | |
self.buffer += bs | |
return len(bs) | |
class InteractiveConsole(BaseInteractiveConsole): | |
"""Интерактивная консоль, возращает вывод выполнения команды""" | |
def __init__(self, locals): | |
"""Принимаем контекст выполнения консоли""" | |
BaseInteractiveConsole.__init__(self, locals) | |
self.stdout = sys.stdout = sys.stderr = Stdout() #Заменяем стандартные потоки собственной реализацией | |
def push(self, line): | |
result = BaseInteractiveConsole.push(self, line) | |
return (result, self.stdout.get_buffer()) #Возвращаем вывод вместе с результатом | |
class Server(SimpleXMLRPCServer): | |
"""XMLRPC-сервер, поставляющий в сеть методы интерактивной консоли""" | |
def __init__(self, ls, *args, **kwargs): | |
SimpleXMLRPCServer.__init__(self, *args, **kwargs) | |
self.register_introspection_functions() | |
self.register_instance(InteractiveConsole(ls)) #Регистрируем экземпляр консоли как обработчик с передачей контекста |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment