Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This isn't pretty, but it's possible:

  import sys
  if sys.version_info[0] < 3:
      print("Needs Python 3+")
      sys.exit(1)
  else:
      prog = r'''
  
  def help():
      print("Help: ...")
  
  def do_spam(*args):
      print("spamming")
  
  def main(args):
      match args:
          case [subcommand, *args]:
              return globals()[f'do_{subcommand}'](*args)
          case _:
              return help()
  
  if __name__ == '__main__':
      try:
          status = main(sys.argv[1:])
          sys.exit(int(status if status is not None else 0))
      except Exception as e:
          import traceback
          traceback.print_exc(e)
          sys.exit(1)
  '''
      compile(prog, '', 'exec')
      exec(prog)


Sure, a variation on eval. I still think some sort of BEGIN equivalent would have been nice. But, the optimal time for that has passed, so I'm just complaining anyway :)


i meant exec as in a shell script to replace the current PID, not python exec()




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: