title: Python Keylogger - Not keeping Keyboard Listener open upon execution from CMD
body: <p>BEFORE WE START...</p>
  
  <p>I am fairly new to Python and any assistance or insight would be absolutely great.</p>
  
  <p><b>This is NOT malicious keylogger, nor a virus, and is going to be used by my company to monitor network PCs for security purposes ONLY. It does not send logs and stores the files locally. It will not attempt to remain hidden. I am an enterprise programmer with no malicious intent. Users will be made aware that keystrokes are being monitored, and logs are stored in the user's home directory. </b></p>
  
  <p>My Python works perfectly fine and as expected in the IDLE editor. However upon running the code from the command line, it does not continue to execute and the script exits. </p>
  
  <p>I have attempted to port my code line by line to a different working version, removing any extra content. Adding a single line break or import appears to completely break the script.</p>
  
  <p>The following code works and does not exit upon execution. It continues to log and works as expected. When ran from CMD, the process remains open: </p>
  
  <pre class="lang-py prettyprint-override"><code>
  from os.path import expanduser
  home = expanduser("~")
  
  from pynput.keyboard import Key, Listener
  import logging
  log_dir = r"{}/".format(home)
  logging.basicConfig(filename = (log_dir + "log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
  def on_press(key):
      logging.info(str(key))
  with Listener(on_press=on_press) as listener:
      listener.join()
  
  </code></pre>
  
  <p>However the following code does not continue to log after execution and the program exits: </p>
  
  <pre class="lang-py prettyprint-override"><code>
  from pynput.keyboard import Key, Listener
  import time
  import os
  import random
  import requests
  import socket
  import platform
  import win32api
  import wmi
  import urllib.request
  import logging
  
  from os.path import expanduser
  homeDir = expanduser("~")
  
  SystemType = platform.system()
  SystemArchitecture = platform.machine()
  SystemPlatform = platform.platform()
  SystemProcessor = platform.processor()
  VolumeInformation = win32api.GetVolumeInformation("C:\\")
  HostName = socket.gethostname()
  SystemWMI = wmi.WMI()
  
  publicIP = requests.get('https://api.ipify.org').text
  privateIP = socket.gethostbyname(socket.gethostname())
  user = os.path.expanduser('~').split('\\')[2]
  datetime = time.ctime(time.time())
  
  file = open(homeDir + "\logger.txt", "w+")
  
  file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
  print("Hostname: " + HostName)
  file.write("Hostname: " + HostName + "\n")
  
  print("User: " + user)
  file.write("User: " + user + "\n")
  
  print("Public IP: " + publicIP)
  file.write("Public IP: " + publicIP + "\n")
  
  print("Private IP: " + privateIP)
  file.write("Private IP: " + privateIP + "\n")
  
  for interface in SystemWMI.Win32_NetworkAdapterConfiguration (IPEnabled=1):
      print("MAC Address: " + interface.MACAddress)
      file.write("MAC Address: " + interface.MACAddress + "\n")
      print("Interface Description: " + interface.Description)
      file.write("Interface Description: " + interface.Description + "\n\n")
  
  print()
  file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
  if(SystemType == "Windows"):    
      print("System Type: " + SystemType)
      file.write("System Type: " + SystemType + "\n")
  
      print("System Architecture: " + SystemArchitecture)
      file.write("System Architecture: " + SystemArchitecture + "\n")
  
      print("System Platform: " + SystemPlatform)
      file.write("System Platform: " + SystemPlatform + "\n")
  
      print("System Processor: " + SystemProcessor)
      file.write("System Processor: " + SystemProcessor + "\n\n")
  
      DriveList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      ActiveDrives = ['%s:' % d for d in DriveList if os.path.exists('%s:' % d)]
  
      DRIVE_TYPES = {
        0 : "Unknown",
        1 : "No Root Directory",
        2 : "Removable Disk",
        3 : "Local Disk",
        4 : "Network Drive",
        5 : "Compact Disc",
        6 : "RAM Disk"
      }
  
      print()
      file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
      print("Drives In Use: ")
      file.write("Drives In Use: \n")
  
      print(ActiveDrives)
      file.write(str(ActiveDrives) + "\n\n")
  
      print()
      file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
      print("Drive Types: ")
      file.write("Drive Types: \n\n")
  
      for drive in SystemWMI.Win32_LogicalDisk ():
          print(drive.Caption, DRIVE_TYPES[drive.DriveType])
          file.write(drive.Caption)
          file.write(DRIVE_TYPES[drive.DriveType] + "\n")
  
      print()
      file.write("\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
      print("C:\\ Volume Information")
      file.write("C:\\ Volume Information: \n")
  
      print(VolumeInformation)
      file.write(str(VolumeInformation) + "\n\n")
  
      print()
      file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
      print("OS Instance Information: ")
      file.write("OS Instance Information: \n")
  
      for os in SystemWMI.Win32_OperatingSystem():
          print(os)
          file.write(str(os) + "\n")
  
  print()
  file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
  
  print("Logging keystrokes...")
  file.write("Logging keystrokes...\n\n")
  
  file.close()
  
  log_dir = r"{}/".format(homeDir)
  logging.basicConfig(filename = (log_dir + "logger.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
  
  def on_press(key):
      print(key)
      logging.info(str(key))
  
  with Listener(on_press=on_press) as listener:
      listener.join()
  
  
  </code></pre>
  
  <p>Even adding a single import to the working version breaks it. There are no exceptions thrown. </p>
  
  <p>The code is expected to continue to log keystrokes after execution, however is exiting without any error codes. It works as expected in IDLE and continues to log until IDLE is closed. However when ran from CMD it closes right after it outputs "Logging Keystrokes...".</p>
  
  <p>Help?</p>