-
Notifications
You must be signed in to change notification settings - Fork 115
feat (#746): Реализована возможность чтения из скрипта данных, переданных через stdin #1086
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat (#746): Реализована возможность чтения из скрипта данных, переданных через stdin #1086
Conversation
…ых, переданных через stdin.
| ConsoleInput.CopyTo(StandartInput); | ||
| ConsoleInput.Close(); | ||
| } | ||
| RegisterProperty("СтандартныйПотокВвода", () => StandartInput); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Давай сделаем это не глобальным свойством, а в классе Консоль? Не хочется занимать глобальный неймспейс без нужды... @nixel2007 @artbear @dmpas @Infactum - реквестирую консилиум.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А в таком случае, как должно выглядеть обращение из скрипта?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
я могу поделиться примерами из java.
Обычно работа с потоком ввода идет через объект System.in, который держит ссылку на InputStream, у которого есть read-методы по чтению сырых байтов. При этом есть класс Console, ссылка на который лежит там же в System.console(). Там методы уже покрасивее, есть readLine, format, readPassword и прочая красота.
При этом запись в stdout может выполняться как из System.out так и из System.console().
System.in появился в 1.1, то есть грубо говоря на заре появления джавы. Console - уже в 1.6, то есть некоторого после взятия за голову.
Но на практике напрямую из потоков и/или консоли все равно никто не читает, а оборачивают обращения к System.in через вызовы Scanner (который умеет readInt, readFloat и прочее) либо в InputStreamReader.
Занимать глобальный нэймспэйс точно не хочется. Перенести поток в Консоль выглядит вполне логично и похоже на ту же джаву. Поток же все равно нельзя будет получить, если скрипт запущен не из терминала, да? помню, что обращение к Консоль падает при запуске в определенных вне-терминальных окружениях. Не будет ли здесь проблем?
| MemoryStreamContext StandartInput = MemoryStreamContext.Constructor(); | ||
| if (Console.IsInputRedirected) | ||
| { | ||
| GenericStream ConsoleInput = new GenericStream(Console.OpenStandardInput(), true); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне больше нравится API Console.OpenStandardInput() который вызывается, как метод-действие по требованию.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ты предлагаешь, сделать типа:
Консоль = Новый Консоль();
Консоль.ПолучитьСтандартныйВвод();?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да. Консоль.ОткрытьПотокВвода(), например
|
Хм, чот на Linux не отрабатывает. :-( |
Все что угодно. Как именно оно не отрабатывает? Ругается на что-то? Есть тексты ошибок? |
Просто не получает данные с stdin. Без ошибок. Руками не запускал, просто тесты посмотрел. |
|
Я не знаю. Предлагаю копать дальше. Погуглить известные баги в mono или core (смотря под чем гоняешь тесты) |
Да, конечно, буду ковырять. А тесты я на твоем Женькинсе смотрел :-). |
feat: ConsoleContext сделан синглтоном; Добавлено глобальное свойство "Консоль".
|
@EvilBeaver Переделал. |
| RegisterProperty("FileStreams", () => FileStreams); | ||
|
|
||
| RegisterProperty("Символы", () => (IValue)Chars); | ||
| RegisterProperty("Символы", () => (IValue)Chars); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот сюда бы добавить свойство Консоль, чтобы был глобальный синглтон. @dmpas, что думаешь?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот сюда бы добавить свойство Консоль, чтобы был глобальный синглтон. @dmpas, что думаешь?
Уже сразу в тестах нарвался на 'Консоль = Новый Консоль()' боюсь, что много где может вылезти.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
может не глобальный, а через враппер? типа Система?
я помню, что вы наоборот выносили из системной информации всякие методы и свойства наружу, но может просто было нехорошее имя?
| return new ConsoleContext(); | ||
| if (_console == null) | ||
| { | ||
| lock (_lock) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lock не нужен, см. статью Скита про синглоны. Нужно создать пустой статик конструктор и обычное статическое поле. https://csharpindepth.com/articles/singleton
Варианты 5 и 6
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Опять же оставил конструктор, чтобы не ломать совместимость. С lock посмотрю.
| public static ConsoleContext Constructor() | ||
| { | ||
| return new ConsoleContext(); | ||
| if (_console == null) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
если это попытка в DLC, то в мультитреде оно работает не так, как ты ожидаешь.
# Conflicts: # src/ScriptEngine.HostedScript/Library/ConsoleContext.cs
| /// Возвращает или задает кодировку консоли, используемую при чтении входных данных. | ||
| /// </summary> | ||
| /// <returns>КодировкаТекста</returns> | ||
| [ContextProperty("КодировкаВыходногоПотока", "InputEncoding")] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Наверное "КодировкаВходногоПотока".
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нет, тут именно Выходного. Их там две. Но английский синоним забыл поменять после копипасты. Спасибо
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Угу, не туда посмотрел.
Реализована возможность чтения из скрипта данных, переданных через stdin.
test.os
Запускаем:
Вывод: