admin管理员组文章数量:1319475
I want to make a program that prompts the user to enter something with an introduction text. Something like "Please write something". But if there is a text from a pipe, the result is displayed directly without any introduction test.
I started a program that read input and answer to the user in Ocaml. But how to make it detecting the absence of pipe ?
If something is piped to that program the introduction text doesn't make sense.
open In_channel
let answer inp =
match inp with
None -> "this is None" |
Some "" -> "this is empty" |
Some x -> "you wrote " ^ x
let () =
print_endline "Please write something" ;
print_endline (answer (input_line stdin) ^ "\nend")
It's not a big deal if the solution is Unix only. Thank you in advance.
I want to make a program that prompts the user to enter something with an introduction text. Something like "Please write something". But if there is a text from a pipe, the result is displayed directly without any introduction test.
I started a program that read input and answer to the user in Ocaml. But how to make it detecting the absence of pipe ?
If something is piped to that program the introduction text doesn't make sense.
open In_channel
let answer inp =
match inp with
None -> "this is None" |
Some "" -> "this is empty" |
Some x -> "you wrote " ^ x
let () =
print_endline "Please write something" ;
print_endline (answer (input_line stdin) ^ "\nend")
It's not a big deal if the solution is Unix only. Thank you in advance.
Share Improve this question edited Jan 19 at 21:47 Chris 36.7k5 gold badges32 silver badges54 bronze badges asked Jan 19 at 20:28 PloumploumPloumploum 3331 silver badge10 bronze badges 1 |1 Answer
Reset to default 2A very straightforward modification to your code based on using Unix.isatty
to determine whether or not to print the prompt.
open In_channel
let answer = function
None -> "this is None"
| Some "" -> "this is empty"
| Some x -> "you wrote " ^ x
let () =
if Unix.isatty stdin then
print_endline "Please write something";
print_endline (answer (input_line stdin));
print_endline "end"
As of OCaml 5.1 (released Sept 2023) In_channel.isatty
exists, and you've already opened In_channel
, so you could reduce the above to:
open In_channel
let answer = function
None -> "this is None"
| Some "" -> "this is empty"
| Some x -> "you wrote " ^ x
let () =
if isatty stdin then
print_endline "Please write something";
print_endline (answer (input_line stdin));
print_endline "end"
本文标签: ioIs it possible to know if a text input is from a pipe onlyStack Overflow
版权声明:本文标题:io - Is it possible to know if a text input is from a pipe only - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742059830a2418514.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
isatty stdin
. – Naïm Favier Commented Jan 19 at 20:43