# Accepting script input via redirection, pipes, or input files
import fileinput

with fileinput.input() as f_input:
  for line in f_input:
    print(line, end='')
    
# ls | ./filein.py
# ./filein.py /etc/passwd
# ./filein.py < /etc/passwd

# Terminating program w/ error message
raise SystemExit('It failed!')

# Parsing CLI options
import argparse
parser = argparse.ArgumentParser(description='Search some files')
parser.add_argument(dest='filename',metavar='filename', nargs='*')
parser_add_argument('-p', '--pat', metavar='pattern', required=True, dest='patterns', action='append', help='text pattern to search for')
args = parser.parse_args()

# Prompting for password at runtime
import getpass

user = getpass.getuser() # Gets username via user's login name.  Prompt via input() if desired.
passwd = getpass.getpass()

if svc_login(user, passwd):
  print('Yay!')
else:
  print('Nay!')

# Execute external command and get its results
import subprocess
out_bytes = subprocess.check_output(['netstat','-a'])
out_text = out_bytes.decode('utf-8')

# Execute external command and send it input
text = b'''
hello world
this is a test
goodbye
'''

p = subprocess.Popen(['wc'], stdout = subprocess.PIPE, stdin = subprocess.PIPE)
stdout, stderr = p.communicate(text)
out = stdout.decode('utf-8')
err = stderr.decode('utf-8')

# Note: subprocess is not suitable for external cmds that expect proper TTY, e.g. ssh session.  For that, use pexpect

# Move and copy directories
import shutil
shtuil.copy(src, dst) # cp src dst
shutil.copy2(src, dst) # cp -p src dst
shutil.copytree(src, dst) # cp -R src dst
shutil.move(src, dst) # mv src dst

# ignore certain files nad dirs during copy
def ignore_pyc(dirname, filenames):
  return [name in filenames if name.endswith('.pyc')]
shutil.copytree(src, dst, ignore=ignore_pyc)

shutil.copytree(src, dst, ignore=shutil.ignore_patterns('~*', '*.pyc'))

# Create or unpack archives
shutil.unpack_archive('Python-3.3.0.tgz')
shutil.make_archive('py33', 'zip', 'Python-3.3.0')
shutil.get_archive_formats() 

# Find files by name
import os

def findfile(start, name):
  for relpath, dirs, files in os.walk(start): # <- Note usage of os.walk
    if name in files:
      full_path = os.path.join(start, relpath, name)
      print(os.path.normpath(os.path.abspath(full_path)))

# Basic Logging
import logging
logging.basicConfig(filename='app.log', level=logging.ERROR)
hostname = 'www.python.org'
item = 'spam'
logging.critical(f"Host {hostname} unknown")
logging.error("This is a error message!")
logging.warning("Feature Depreciated")
logging.info("Opening file")
logging.debug("Breakpoint 5")
  
# Configure logging via INI file
import logging.config
logging.config.fileConfig('logconfig.ini')

# FILE: logconfig.ini
#
# [loggers]
# keys=root
# [handlers]
# keys=defaultHandler
# [formatters]
# keys=defaultFormatter
# [logger_root]
# level=INFO
# handlers=defaultHanlder
# qualname=root
# [handler_defaultHandler]
# class=FileHandler
# formatter=defaultFormatter
# args=('app.log'), 'a'
# [formatter_defaultFormatter]
# format=%(levelname)s:%(name)s:%(message)s

# Launch web browser
import webbrowser
webbrowser.open('http://www.python.org')
webbrowser.open_new_tab('http://www.python.org')

