def main(): argdoc.parse_args() # Print banner # in place of popular def prompt_tty_stdin stderr_print() stderr_print( "dd.py: Press ⌃T SIGINFO to see progress, a la Linux: killall -SIGUSR1 python3" ) stderr_print( "dd.py: Press ⌃Z to pause, and then tell Bash to 'fg' to resume") stderr_print( r"dd.py: Press ⌃C SIGINT to quit, press ⌃\ SIGQUIT if you really mean it" ) stderr_print("Press ⌃D EOF to quit") stderr_print() # Define SIGINFO def siginfo(signum, frame): stderr_print("dd.py: ⌃T SIGINFO") with SigInfoHandler(siginfo): # Serve till EOF or SIGINT drop_sigint_once = True while True: # Pull one line try: line = sys.stdin.readline() except KeyboardInterrupt: if not drop_sigint_once: stderr_print() break drop_sigint_once = False stderr_print( "dd.py: KeyboardInterrupt: Thank you for SIGINT, press it again if you mean it" ) continue # FIXME: ⌃C SIGINT inside "dd.py" inside "bash.py" chokes drop_sigint_once = True # Exit at end-of-file if not line: stderr_print("dd.py: ⌃D EOF") break print(line.rstrip()) # FIXME: call for larger buffer inside "dd"
def main(): args = argdoc.parse_args() if not args.dirs: stderr_print("mkdir.py: error: mkdir of zero args not implemented") sys.exit(2) # exit 2 from rejecting usage exit_status = None for dir_ in args.dirs: if os.path.isdir(dir_): if not args.parents: stderr_print( "mkdir.py: error: cannot create a dir that exists: {}". format(dir_)) exit_status = 1 continue try: if args.parents: os.makedirs(dir_) else: os.mkdir(dir_) except OSError as exc: stderr_print("mkdir.py: error: {}: {}".format( type(exc).__name__, exc)) exit_status = 1 sys.exit(exit_status)
def main(argv): pwd_argv_tail = argv[1:] if argv[1:] else ["--home" ] # FIXME: more robust default args = argdoc.parse_args(pwd_argv_tail) pwd = os.environ["PWD"] abspath = os.path.abspath(pwd) realpath = os.path.realpath(pwd) try: gotcwd = os.getcwd() except FileNotFoundError as exc: print(pwd) stderr_print("pwd.py: error: {}: {}".format(type(exc).__name__, exc)) sys.exit( 1) # FIXME: more robust "pwd" vs the current working dir deleted assert gotcwd == realpath path = realpath if args.physical else abspath # FIXME: count -L -P contradictions formatter = min_path_formatter_not_relpath(path) briefpath = formatter(path) homepath = os_path_homepath(path) printable = path if args.home: printable = homepath elif args.brief: # FIXME: count -H -B contradictions printable = briefpath print(printable)
def main(argv): args = argdoc.parse_args(argv[1:]) passme.sponging = False passme.print_lines = list() if args.csv: passme.sponging = True # Expand each file paths = args.files if args.files else ["-"] if "-" in paths: prompt_tty_stdin() for path in paths: readable = "/dev/stdin" if (path == "-") else path try: with open(readable, "rb") as incoming: expand_incoming(incoming, args=args) except FileNotFoundError as exc: stderr_print("expand.py: error: {}: {}".format( type(exc).__name__, exc)) sys.exit(1)
def main(): args = argdoc.parse_args() # Fetch files = args.files if args.files else "-".split() for path in files: if path == "-": prompt_tty_stdin() chars = sys.stdin.read() else: with open(path) as incoming: chars = incoming.read() # Munge stdout = "\n" if chars: bits = json.loads(chars) stdout = json.dumps(bits) + "\n" # Store sys.stdout.write(stdout)
def _parse_read_argv(argv): """Parse the command line""" args = argdoc.parse_args() # Default to no splatter, else Ascii splat "*" splatter, to show input length not choice splatter = None if args.splat is not False: splatter = "*" if (args.splat is None) else args.splat args.splatter = splatter # Fail fast if wrongly called to silence or splatter while not in control of echoing echoing = args.e or (not sys.stdin.isatty()) if not echoing: # FIXME: learn to silence without -e when stdin is a tty if args.s or splatter: stderr_print( "read.py: error: call for -es, not -s, when stdin is a tty") sys.exit(2) # exit 2 from rejecting usage # Choose a prompt args.prompting = "? " if (args.prompt is None) else args.prompt return args
def main(argv): """Interpret a command line""" # Parse the command line tar_argv_tail = list(argv[1:]) if argv[1:] and not argv[1].startswith("-"): tar_argv_tail[0] = "-{}".format(argv[1]) args = argdoc.parse_args( tar_argv_tail if tar_argv_tail else "--help".split()) # Require -tvf or -xvkf tvf = args.t and args.v and args.file xvkf = args.x and args.v and args.k and args.file if not (tvf or xvkf): stderr_print_usage_error(args) sys.exit(2) # exit 2 from rejecting usage # Interpret -tvf or -xvkf args_file = args.file if args.file == "-": args_file = "/dev/stdin" prompt_tty_stdin() tar_file_tvf_xvkf(args_file, args_x=args.x)
def builtin_history(argv): """ usage: history [-h] review command line input history optional arguments: -h, --help show this help message and exit examples: history """ doc = textwrap.dedent(builtin_history.__doc__).strip() try: _ = argdoc.parse_args(args=argv[1:], doc=doc) except SystemExit as exc: returncode = exc.code return returncode shlines = read.ShLineHistory.shlines # couple less tightly # add date/time-stamp's for (index, shline) in enumerate(shlines): lineno = 1 + index print("{:5d} {}".format(lineno, shline))
def main(): """Run from the command line""" args = argdoc.parse_args() if not args.t: stderr_print(argdoc.format_usage().rstrip()) stderr_print("column.py: error: no arguments not implemented") sys.exit(2) # exit 2 from rejecting usage # Fetch all of Stdin prompt_tty_stdin() lines = sys.stdin.readlines() # Divide each line into words split_lines = list(_.split() for _ in lines) # Discard empty lines rows = list(row for row in split_lines if row) # Justify the cells in each column justified_rows = justify_cells_in_rows(complete_rows(rows, cell="")) for justified_row in justified_rows: print(" ".join(justified_row).rstrip())
def main(argv): tr_argv_tail = argv[1:] if argv[1:] else [ "--unique-everseen", "--sort", "" ] args = argdoc.parse_args(tr_argv_tail) args_charset = args.charset if args.charset else "" charset = None if args_charset == r"[^ -~]\t\r\n": codes = list(range(ord(" "), (ord("~") + 1))) codes.extend([ord("\t"), ord("\r"), ord("\n")]) charset = "".join(chr(_) for _ in codes) elif not any(_ in args_charset for _ in r"\[]"): charset = args_charset if charset is None: stderr_print( "usage: tr.py [-h] [-d] [--sort] [--unique-everseen] [CHARSET]") stderr_print( "tr.py: error: not much usage implemented") # FIXME: shlex.join sys.exit(2) # exit 2 from rejecting usage stdins = sys.stdin.read() # FIXME: "utf-8", errors="surrogateescape" takes = stdins if args.delete: takes = list(_ for _ in stdins if _ not in charset) uniques = str_unique_everseen(takes) stdouts = uniques if args.sort: # sorted(str_unique_everseen.charset) could be faster stdouts = "".join(sorted(uniques)) sys.stdout.write("".join(stdouts))
def main(argv): args = argdoc.parse_args(argv[1:]) if args.e: args.show_ends = True args.show_nonprinting = True if args.t: args.show_tabs = True args.show_nonprinting = True paths = args.files if args.files else ["-"] # Catenate each binary (or text) file if "-" in paths: prompt_tty_stdin() for path in paths: readable = "/dev/stdin" if (path == "-") else path try: with open(readable, mode="rb") as incoming: cat_incoming(fd=incoming.fileno(), args=args) except FileNotFoundError as exc: stderr_print("cat.py: error: {}: {}".format( type(exc).__name__, exc)) sys.exit(1)
def _parse_hexdump_argv(argv): """Parse the command line""" args = argdoc.parse_args(argv[1:]) args.classic = (args.bytes is False) and (args.charset is False) # args.stride = 1 if (args.bytes is not None) and (args.bytes is not False): args.stride = int(args.bytes, 0) # args.encoding = args.C or (args.charset is not False) args.decoding = None far_codec_hint = "utf-8" if args.charset is not False: args.decoding = True if args.charset: far_codec_hint = args.charset if args.bytes is not False: stderr_print(argdoc.format_usage().rstrip()) stderr_print( "hexdump.py: error: choose --charset or --bytes, not both") sys.exit(2) # exit 2 from rejecting usage "".encode(far_codec_hint) # may raise LookupError: unknown encoding near_codec_hint = far_codec_hint.replace("-", "_").lower() ascii_codec_hints = "ascii 646 us_ascii" utf_8_codec_hints = "utf_8 u8 utf utf8 cp65001".split() latin_1_codec_hints = ( "latin_1 iso_8859_1 iso8859_1 8859 cp819 latin latin1 l1".split()) args.codec = far_codec_hint if near_codec_hint in ascii_codec_hints: args.codec = "ascii" elif near_codec_hint in latin_1_codec_hints: args.codec = "latin-1" elif near_codec_hint in utf_8_codec_hints: args.codec = "utf-8" else: stderr_print(argdoc.format_usage().rstrip()) stderr_print( "hexdump.py: error: choose --charset from: ascii, latin-1, utf-8") sys.exit(2) # exit 2 from rejecting usage # return args
def main(argv): args = argdoc.parse_args() if args.hows: stderr_print("find.py: error: Got undefined hints: {}".format(args.hows)) sys.exit(-1) try: print_os_walk_minpaths(args.top) except KeyboardInterrupt: sys.exit(0x80 + signal.SIGINT) # "128+n if terminated by signal n" <= man bash
def main(argv): chmod_argv_tail = argv[1:] if argv[1:]: if argv[1].startswith("-") and not argv[1].startswith("-R"): chmod_argv_tail[0:0] = ["--"] args = argdoc.parse_args(chmod_argv_tail) sys.stderr.write("{}\n".format(args)) sys.stderr.write("{}\n".format(argdoc.format_usage().rstrip())) sys.stderr.write("chmod.py: error: not implemented\n") sys.exit(2) # exit 2 from rejecting usage
def main(argv): args = argdoc.parse_args() if args.verbose: print(args.words, file=sys.stderr) line = " ".join(args.words) if args.n: sys.stdout.write(line) else: print(line)
def main(argv): """Run from the command line""" args = argdoc.parse_args(argv[1:]) main.args = args stderr_print(args) stderr_print(argdoc.format_usage().rstrip()) stderr_print("watch.py: error: not implemented") sys.exit(2) # exit 2 from rejecting usage main.era = datetime.datetime.now() last_result = None next_call = main.era while True: when_called = datetime.datetime.now() result = check_transcript(args.words) when_returned = datetime.datetime.now() if result != last_result: last_result = result sys.stdout.write( "\x1B[H\x1B[2J") # Ansi Clear from $(clear | cat -tv) sys.stdout.write( "\n") # end the line to keep the 'screen' text 'grep'pable (exit_status, out_bytes) = result print("{} + N * {}".format( when_called, datetime.timedelta(seconds=args.interval))) print() print("+ {}".format(shlex_join(args.words))) sys.stdout.write(out_bytes) print("+ exit {}".format(exit_status)) print() print("{} - {}".format(when_returned, (when_returned - when_called))) sys.stdout.flush() while next_call < datetime.datetime.now(): next_call += datetime.timedelta(seconds=args.interval) next_call += datetime.timedelta(seconds=args.interval) sleepy = (next_call - datetime.datetime.now()).total_seconds() assert sleepy > 0 time.sleep(sleepy)
def main(): args = argdoc.parse_args() if args.status is None: sys.exit() status = int(args.status) if not (-0x80 <= status <= 0x7F): partial = status & 0xFF sys.stderr.write("exit.py: error: returning {} as {}\n".format( status, partial)) sys.exit(status)
def main(argv): args = argdoc.parse_args() words = args.words verb = ShVerb() if words: verb = ShVerb(words[0]) verbed = verb(*words[1:]) pprint.pprint(verbed.vars) exit_status = verbed sys.exit(exit_status)
def main(): """Interpret a command line""" stdout_isatty = sys.stdout.isatty() stdout_columns = sys_stdout_guess_tty_columns() # stderr_print("stdout_columns={}".format(stdout_columns)) args = argdoc.parse_args() correct_args(args, stdout_isatty=stdout_isatty, stdout_columns=stdout_columns) tops = args.tops if args.tops else [os.curdir] for index in range(len(tops)): print_one_top_walk(tops=tops, index=index, args=args) if args.directory: break
def main(): """Interpret a Cal command line""" args = argdoc.parse_args() args.color = sys.stdout.isatty() and not args.h # FIXME: make --color=yes easy to say when not isatty main.args = args now = dt.datetime.now() today = dt.datetime(now.year, now.month, now.day, 12, 00) # duck 2am DST etc if args.ymd: today = misread_ymd_12n(args.ymd) two_weeks_back = today - dt.timedelta(weeks=2) two_weeks_ahead = today + dt.timedelta(weeks=2) week = when_last_12n(two_weeks_back, weekday=cal.MONDAY) month = week.month print_start_of_month(week.replace(day=1), week) if week.day > 1: print_rstripped("...".center(WIDTH)) while week < two_weeks_ahead: end_of_week = week_last_day(week) if month != week.month: month = week.month print_start_of_month(week.replace(day=1), week=week) print_week_in_month(week, month=month, today=today) if end_of_week.month != month: month = end_of_week.month print_start_of_month(end_of_week.replace(day=1), week=week) print_week_in_month(week, month=month, today=today) week += dt.timedelta(weeks=1) if month == (end_of_week + dt.timedelta(days=1)).month: print_rstripped("...".center(WIDTH)) print()
def main(argv): args = argdoc.parse_args() if not args.interact: stderr_print(argdoc.format_usage().rstrip()) stderr_print("bash.py: error: choose --interact") sys.exit(2) # exit 2 from rejecting usage # Print banner stderr_print() stderr_print("Pybashish 0.x.y for Linux and Mac OS Terminals") stderr_print('Type "help" and press Return for more information.') stderr_print( 'Type "exit" and press Return to quit, or press ⌃D EOF to quit') stderr_print() # Serve till exit main.returncode = None while True: # Pull one line of input prompt = calc_ps1() try: shline = read.readline(prompt) except KeyboardInterrupt: continue # Exit at end-of-file # Exit with same subprocess.CompletedProcess.returncode=1 as Bash exit at EOF if not shline: sys.exit(1) # Compile and execute the line returncode = compile_and_run_shline(shline) main.returncode = returncode if returncode: # trace nonzero a la Zsh "print_exit_value" stderr_print("bash.py: warning: exit {}".format(returncode))
def main(): args = argdoc.parse_args() args.j = args.ymd # FIXME: solve argdoc for when multiple options have same arg YMD if None not in (args.j, args.date): stderr_print("date.py: error: choose -j or --date, not both") sys.exit(2) # exit 2 from rejecting usage if args.j: now = misread_ymdhms_mac(args.j) elif args.date: now = misread_ymdhms_linux(args.date) else: now = dt.datetime.now() stdout = now.strftime("%Y-%m-%d %H:%M:%S.%f") print(stdout)
def main(): """Run from the command line""" args = argdoc.parse_args() stdin = sys.stdin.read() words = stdin.split() len_words = len(words) words_per_line = len_words if (args.max_args is None) else int( args.max_args) if len_words: for index in range(0, len_words, words_per_line): argv_tail = words[index:][:words_per_line] stdout = "{}\n".format(" ".join(argv_tail)) sys.stdout.write(stdout)
def main(): args = argdoc.parse_args() main.args = args if (args.force, args.interact) == (0, 0): stderr_print(argdoc.format_usage().rstrip()) stderr_print("cspsh.py: error: choose --force or --interact") sys.exit(2) # exit 2 from rejecting usage lines = list() if args.force: lines = textwrap.dedent(TEST_LINES).strip().splitlines(keepends=True) lines.append("") if args.command is not None: lines.append(args.command + "\n") lines.append("") run_cspvm(lines, args=args)
def main(): # Parse args args = argdoc.parse_args() if (args.dir is None) or (args.dir == "~"): path = os.environ["HOME"] elif args.dir == "-": try: path = os.environ["OLDPWD"] except KeyError: sys.stderr.write("cd.py: error: OLDPWD not set\n") sys.exit( 1 ) # classic exit status 1 for violating this env var precondition else: path = args.dir if args.dir.startswith("~"): path = os.environ["HOME"] + args.dir[1:] dry_run_cd(path, args=args)
def main(argv): # Parse args args = argdoc.parse_args() args.vq = (args.verbose if args.verbose else 0) - (args.quiet if args.quiet else 0) if args.files != ["tests/"]: stderr_print("usage: doctestbash.py [-h] [-b] [-q] [-v] tests/") stderr_print( "doctestbash.py: error: more arbitrary arguments not implemented") sys.exit(2) # exit 2 from rejecting usage main.args = args # Test the one well known file assert args.files == ["tests/"] file_dir = os.path.split(__file__)[0] tests_dir = os.path.join(file_dir, os.pardir, "tests") tests_path = os.path.join(tests_dir, "pybashish.typescript") path = os.path.relpath( tests_path) # abbreviate as relpath for tracing later with open(path) as incoming: passes = _run_bash_test_doc(incoming, path=path) # Declare success if not args.rip_bash_paste: stderr_print("doctestbash.py: {} tests passed at: {}".format( passes, path)) # Call one Python Doc Test, just to help people reviewing the code find that precedent _show_doctest_result()
def main(): args = argdoc.parse_args() if not args.files: stderr_print("touch.py: error: touch of zero args not implemented") sys.exit(2) # exit 2 from rejecting usage exit_status = None for file_ in args.files: if not os.path.exists(file_): with open(file_, mode="w"): pass continue try: os.utime(file_) except OSError as exc: stderr_print("touch.py: error: {}: {}".format(type(exc).__name__, exc)) exit_status = 1 sys.exit(exit_status)
def main(argv): args = argdoc.parse_args(argv[1:]) paths = args.files if args.files else ["-"] # Catenate each binary (or text) file prompt_tty_stdin() with open("/dev/stdin", mode="rb") as incoming: sponge = incoming.read() for path in paths: writable = "/dev/stdout" if (path == "-") else path try: awb_mode = "ab" if args.append else "wb" with open(writable, mode=awb_mode) as outgoing: os.write(outgoing.fileno(), sponge) except FileNotFoundError as exc: stderr_print("sponge.py: error: {}: {}".format( type(exc).__name__, exc)) sys.exit(1)
def main(): # Parse args args = argdoc.parse_args() confidence = args.force - args.interact args_force = confidence if (confidence > 0) else 0 args_interact = -confidence if (confidence < 0) else 0 finesse = args.quiet - args.verbose args_quiet = finesse if (finesse > 0) else 0 args_verbose = -finesse if (finesse < 0) else 0 args_lines = list() if args.command is not None: args_lines = args.command.splitlines() if not args.command.strip(): args_lines = [""] # Test, if not interacting if not args_interact: test_cspsh() if not args_lines: if args_force: return # Run run_cspsh( args_lines=args_lines, args_interact=args_interact, args_quiet=args_quiet, args_verbose=args_verbose, )
def main(argv): """Run one split command line""" argv_tail = list() for (index, arg) in enumerate(argv): if index: if arg == "--": # accept negated numbers as not dash options argv_tail.extend(argv[index:]) break if re.match(r"^[-]?[0-9]", string=arg): argv_tail.append("--") argv_tail.extend(argv[index:]) break argv_tail.append(arg) # if argv_tail != argv[1:]: # stderr_print("+ , {}".format(shlex.join(argv_tail))) args = argdoc.parse_args(argv_tail) hints = args.hints if hints: hint = hints[0] if hint in HINTS_BY_HINT: hints = args.hints[1:] + HINTS_BY_HINT[hint] if len(hints) > 2: stderr_print(", " + " ".join(hints)) pb_lines = resume_from_pb() pbvm = PbVirtualMachine(pb_lines) pbvm.walk_hints(hints) suspend_to_pb(pbvm.pb_lines)