Identifying the data type of an input

from ast import literal_eval def get_type(input_data): try: return type(literal_eval(input_data)) except (ValueError, SyntaxError): # A string, so return str return str print(get_type(“1”)) # <class ‘int’> print(get_type(“1.2354”)) # <class ‘float’> print(get_type(“True”)) # <class ‘bool’> print(get_type(“abcd”)) # <class ‘str’>

When is it best to sanitize user input?

Unfortunately, almost no one of the participants ever clearly understands what are they talking about. Literally. Only Kibbee managed to make it straight. This topic is all about sanitization. But the truth is, such a thing like wide-termed “general purpose sanitization” everyone is so eager to talk about is just doesn’t exist. There are a … Read more

Python – Infinite while loop, break on user input

You can use non-blocking read from stdin: import sys import os import fcntl import time fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK) while True: print(“Waiting for user input”) try: stdin = sys.stdin.read() if “\n” in stdin or “\r” in stdin: break except IOError: pass time.sleep(1)

How to supply stdin, files and environment variable inputs to Python unit tests?

All three situations you’ve described are where you need to specifically go out of your way to ensure you are using loose coupling in your design. Do you really need to unit test Python’s raw_input method? The open method? os.environ.get? No. You need to set up your design so that you can substitute other ways … Read more

How to read an integer input from the user in Rust 1.0?

Here is a version with all optional type annotations and error handling which may be useful for beginners like me: use std::io; fn main() { let mut input_text = String::new(); io::stdin() .read_line(&mut input_text) .expect(“failed to read from stdin”); let trimmed = input_text.trim(); match trimmed.parse::<u32>() { Ok(i) => println!(“your integer input: {}”, i), Err(..) => println!(“this … Read more