Skip to content

Instantly share code, notes, and snippets.

@Bost
Last active August 22, 2017 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bost/4fb9be9c02549d1d5032d2481ea6ab88 to your computer and use it in GitHub Desktop.
Save Bost/4fb9be9c02549d1d5032d2481ea6ab88 to your computer and use it in GitHub Desktop.
python: execute os command
#!/usr/bin/env python
from subprocess import Popen, PIPE
import operator
import os
import re
import datetime
import time
from functools import reduce
from pathlib import Path
def map_f_reduce_add(f, xs):
return reduce(operator.add, map(f, xs), []) # only map and reduce!
def tstp():
""" See also:
import logging
logging.info("Foo")
"""
return datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M%S')
# return code index in the list returned by do_exec
idx_rc = 1
idx_res = 2
def safe_print(cmd_str):
print(re.sub(r"--password\s+\S+", "--password ******", cmd_str))
def do_exec(cmd):
cmd_str = " ".join(list(map(str, cmd)))
safe_print(cmd_str)
p = Popen(cmd_str, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
# output, err = p.communicate(b"input data that is passed to subprocess' stdin")
out, err = p.communicate(b"")
rc = p.returncode
if rc != 0:
print(err.decode("utf-8"))
res = [cmd_str, rc, out]
# out_utf = out.decode("utf-8")
# tsplit = out_utf.split("\n")
# ret = tsplit[0:(len(tsplit) - 1)] # last array item is an empty string
# return ret
return res
files = [
"git.sh",
"linux.sh",
"win.bat",
"clojure.clj",
"emacs.el",
"utf8.txt",
]
def links(f):
target_dir = str(Path.home()) + "/dev/cheatsheet/cmds/"
linkname_dir = target_dir+"crep/"
cmd = ["ln", "--symbolic", target_dir+f, linkname_dir+f]
do_exec(cmd)
# w/o the map(...) into list(...) I get only # <map object at 0x7fa54f2b6048>
list(map(links, files))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment