summaryrefslogtreecommitdiff
path: root/py/util.py
blob: ad5fa625f96e69573c8c2e40e5870e4a9b939acd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from datetime import datetime
import os
import subprocess
from pathlib import Path

#TODO bring code over from complete module

datadir=Path.home() / '.local' / 'share' / 'pyutil'
logdir=datadir / 'log'


def cmd(cmdstr,v=False):
    '''run cmdstr as a command in the shell, return the output'''
    cmdarray = cmdstr.strip().split(' ')
    log(f'runcmd: {cmdstr}')
    #TODO handling pipe not yet working
    proc = subprocess.run(cmdarray, stdout=subprocess.PIPE)
    if proc.returncode == 0:
        res = proc.stdout
    else:
        log(f'returncode = {proc.returncode}')
        res = proc.stderr
    return res

def log(msg):
    d = datetime.now().strftime('%Y%m%d')
    fn = logdir / f'log-{d}.txt'
    if not logdir.exists():
        os.makedirs(logdir, exist_ok=True)
    with open(fn, 'a') as lf:
        lf.write(f'{d}: {msg}\n')
        lf.close()

def tnow():
    '''
    return: current time, formatted as %Y%m%d-%H%M%S
    ''' 
    return datetime.now().strftime('%Y%m%d-%H%M%S')


############################