Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get passed arguments

I'm working on a project which allows the user to set a path to upload files to by adding the necessary argument but for whatever reason, the upload_destination variable is always empty! Here's my code

def main():
  global listen
  global port
  global execute
  global command
  global upload_destination
  global target

  if not len(sys.argv[1:]):
     usage()
  try:
     opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu", ["help", "listen", "execute", "target", "port", "command", "upload"])
  except getopt.GetoptError as err:
     print str(err)
     usage()

  for o,a in opts:
     if o in ("-h", "--help"):
         usage()
     elif o in ("-l", "--listen"):
         listen = True
     elif o in ("-e", "--execute"):
         execute = True
     elif o in ("-c", "--commandshell"):
         command = True
     elif o in ("-u", "--upload"):
         #Here's the problem, a is empty even though I include a path
         upload_destination = a
     elif o in ("-t", "--target"):
         target = a
     elif o in ("-p", "--port"):
         port = int(a)
     else:
         assert False, "Unhandled Option"

  if not listen and len(target) and port > 0:
     buffer = sys.stdin.read()
     client_sender(buffer)

  if listen:
     server_loop()

I call the programm by entering

C:\Users\Asus\Desktop\PythonTest>python test.py -l -c -p 3500 -u C:\Users\Asus\Desktop\Test
like image 322
Aginu Avatar asked May 18 '26 00:05

Aginu


1 Answers

It's a simple missing colon :.

https://docs.python.org/2/library/getopt.html

options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).

Change the "hle:t:p:cu" to "hle:t:p:cu:" and it should work (at least it did work for me with Win7/Python3.5).

When you execute print(opts, args) with your code, you get:

([('-l', ''), ('-c', ''), ('-p', '3500'), ('-u', '')], ['C:UsersAsusDesktopTest'])

with the added colon it becomes:

([('-l', ''), ('-c', ''), ('-p', '3500'), ('-u', 'C:UsersAsusDesktopTest')], [])

Without the colon C:\Users\... becomes a new argument.

like image 138
Maximilian Peters Avatar answered May 20 '26 12:05

Maximilian Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!