#stdin

2025-03-28

Управляем потоками в Linux: от stdin до stderr

Привет, Хабр! Сегодня рассмотрим работу с потоками в Linux: stdin, stdout, stderr и, конечно, все эти оператора редиректа.

habr.com/ru/companies/otus/art

#linux #stdin #stderr #разработка #bash

a66ey 🇪🇺🏳️‍🌈 she/hera66ey
2024-06-19

Custom parser, an unholly aliance of and for processing from more or less works!

Time to up the game 😼

Найменшенькийbalaraz@social.net.ua
2024-02-15

Зазвичай друга програма кожного програміста який починає вивчати мову програмування це hello {name}.

Спочатку треба трохи розʼяснити про ghc, ghci і функцію main.

  • ghc - це компілятор мови програмування Haskell.

  • ghci - це інтерпретатор мови програмування.

  • функція main - це головна функція яка автоматично викликається при запуску бінарного файлу зібраного за допомогою ghc. Вона не обовʼязкова для запуску в режимі інтерпретації.

  • У функціональних мовах, до яких належить Haskell, немає змінних. Є тільки функції та константи. Константа це функція яка повертає завжди одне значення не залежачи від жодних обставин.

  • Всі файли з джерельним кодом називаються модулями. Є спеціальне оголошення модулів, але про це пізніше.

  • Також є різниця між написанням коду в файлі й виконанням в інтерактивному режимі інтерпретатора. В інтерпретаторі ми можемо виконати будь-яку інструкцію, наприклад putStrLn "Hi!", а в модулі ні. У модулі можна тільки створювати функції.

  • Однорядкові коментарі починаються з двох мінусів -- Comment.

Тепер перейдемо до нашої програми. У єдиній попередній нашій функції в нас була одна команда. Виклик функції putStrLn з передаванням аргументу. Тепер нам потрібно вписати кілька команд, і щоб це зробити потрібно використати ключове слово do. Після нього можна вписати кілька команд розділені ;, або новим рядком. Але кожний новий рядок повинен починатися з певного відступу. Відступ може бути або пробілом, або табуляцією. Кількість символів може бути різною, але кожний наступний рядок повинен мати, або ту ж кількість пробілів, або більше. Якщо буде менше, то це вважатиметься новим оголошенням. Також один символ табуляції буде розглядатись як вісім пробілів, не залежно від налаштувань редактора.

main = do
  putStr "Введіть ваше ім'я: " -- Вивід тексту в stdout
  name <- getLine -- зчитування з клавіатури одного рядка з stdin
  putStrLn ("Привіт, " ++ name ++ "!") -- Вивід привітання в stdout

Оператор ++ обʼєднує рядки в один. У інших мовах для цього використовується оператор, який складається з одного символу +.

Все було б добре, якби не одна проблема. Коли ми запустимо цю програму, то отримаємо не зовсім очікуваний результат.

Мертвий Демон
Введіть ваше ім'я: Привіт, Мертвий Демон!

Ця програма спочатку буде очікувати на ввід, а потім виведе на екран весь текст. Це відбувається через буферизацію. Вивід відбувається при вписуванні символу нового рядка. Але ми можемо змусити його вивести тоді коли нам це потрібно. Ця функція називається flush. У Haskell вона знаходиться у модулі System.IO, який нам потрібно імпортувати.

import System.IO

main = do
  putStr "Введіть ваше ім'я: "
  hFlush stdout
  name <- getLine
  putStrLn ("Привіт, " ++ name ++ "!")

Ця програма буде працювати вірно.

#haskell #hello-name #programing #програмування #друга #програма #stdout #stdin #функції #вивід #ввід #екран #клавіатура #зчитування #flush

Todd A. Jacobs | Rubyisttodd_a_jacobs@ruby.social
2023-09-30

#Unix & #Linux #CLI Buffering Tips

I recently posted about some pragmatic differences between #stdbuf from #GNU #coreutils and the #unbuffered command from the #Expect tool examples. Both were installed and tested using #Homebrew on #macOS. The TL;DR is that `unbuffered` is easier and works on #stdin, while `stdbuf` gives you more options for each separate I/O stream.

unix.stackexchange.com/a/75785

2023-06-17

Wrote this #lisp hello world #gui #cloud app last few minutes, just smart enough to draw and exit on right click. Just uses #stdin #stdout output same as the #bash and #C implementations (setq x "Fo 0 999 3\nF 0 255\nL$ 0 0 800\"Hello world\"\nZ \n")
(while (setq p (asc (fgets stdin))) (cond ((== p 100) (write 1 x (strlen x))) ((== p 51) (exit 0)))) This code is out on bitbucket timcdoc antibrowser lisp hello (sub C or bash for lisp to see others)

Hello world lisp gui  cloud app and code
2023-04-24

Graphing part is working, just hard coded fns for now, but it's a start! #lisp #antibrowser #cloud #app #thinclient #NoFont #stdin #stdout [[oh code, my lisp, ancient variant, out on bitbucket.org/timcdoc/antibrow

graph of sin,cos,quadratic and exp.
Jan :rust: :ferris:janriemer@floss.social
2023-04-07

If nothing happens, maybe it waits for stdin? 😉

#Programming #CLI #Debugging #Stdin #Stuck #Tips

2023-01-22

`input` in #python read from #stdin. It's pretty straight forward.

But this is how *most* tools work in Linux. Often times you can give them data on stdin instead of in a file. In Python you might do it like

import sys

if len(sys.argv) > 1:
with open(sys.argv[0]) as f:
data = f.read()
else:
data = sys.stdin.read()

You've gotta .read() from stdin, since `input` just looks for the first newline. Anyway. Piping is a very fundamental part of Linux command line.

2023-01-22

Now remember - so far all of this is just to get two lists - my TableOfContents and all of the WikiWords that exist in my file.

If you use #Linux or #Unix for any period of time (or #GnuLinux - where my pedants at?), you will probably have come across `sort`.

Now we get to talk about streams and files!

Everything in Linux is a file. Which is shockingly powerful. Input from the keyboard? A file you can read from. Output to the screen? A file you can write to. #stdin and #stdout are their names

📡 RightToPrivacy & Tech TipsRTP@fosstodon.org
2022-01-02

Pinephone Keyboard case pictures from the above blog post:
#Pinephone #Keyboard #Pine64 #Linux #Phones #Input #stdin #blog #FOSS

2021-05-08

C++ - MSVCにおいて、標準入力からUTF-8の文字列を入力したい|teratail
teratail.com/questions/336873
#windows #stdin #utf8

2021-05-08

COOKED_READ doesn't return UTF-8 on *A APIs in CP_UTF8 · Issue #4551 · microsoft/terminal
github.com/microsoft/terminal/
#windows #stdin #utf8

2021-05-08
2020-05-03

Wildes #Ausprobieren.

#Was ist #eingeschlossen?
#Was ist #ausgeschlossen?

#stdin #stdout #stderr
#Input / #Output / #Error (Output)

Ein #Fall, in dem ich (noch) nicht #imstande bin, #Anweisung​en einzusehen, ich also nur durch #ausprobieren #herausfinden kann, was ein- und was #ausgeschlossen ist. Keine #Möglichkeit also, (un)vollständigkeit festzustellen

#Einsehen; #Vollständigkeit; #Unvollständigkeit; #Feststellung

Certificação Linuxcertificacaolinux
2019-04-02

Redirecionamentos e Condutores no Linux
Um conceito importante no Linux é o redirecionamento. Como tudo no Linux é um arquivo, fez-se necessário que os comandos e processos tivessem a habilidade de tratar as entradas e saídas de dados com grande facilidade.

Antes de detalharmos a habilidade de redirecionamento do Linux
precisamos defi
certificacaolinux.com.br/redir

Certificação Linuxcertificacaolinux
2019-04-02

Redirecionamentos e Condutores no Linux
Um conceito importante no Linux é o redirecionamento. Como o Linux foi criado por programadores para programadores, fez-se necessário que os comandos e processos tivessem a habilidade de tratar as entradas e saídas de dados com grande facilidade.

Antes de detalharmos a habilidade de redirecioname
certificacaolinux.com.br/redir

2019-01-04

Pour info, le pouet précédent a été écrit via l'entrée standard (#stdin) dans l'interface de la ligne de commande (#CLI) et envoyé avec le client #Toot écrit par @ihabunek. Pour reproduire la manipulation :

```bash
# lit la ligne 1
read line
# lit la ligne 2
read line2
# affiche le pouet en "brouillon"
echo -e "$line\n$line2"
# envoie le pouet
echo -e "$line\n$line2" | toot post
```

Client Info

Server: https://mastodon.social
Version: 2025.04
Repository: https://github.com/cyevgeniy/lmst