Python 获取传递的参数

Python get passed arguments

我正在开发一个项目,该项目允许用户通过添加必要的参数来设置上传文件的路径,但无论出于何种原因,upload_destination 变量始终为空! 这是我的代码

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()

我通过输入

来调用程序
C:\Users\Asus\Desktop\PythonTest>python test.py -l -c -p 3500 -u C:\Users\Asus\Desktop\Test

这是一个简单的缺失冒号 :

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).

"hle:t:p:cu" 更改为 "hle:t:p:cu:",它应该可以工作(至少它对我 Win7/Python3.5 有效)。

当您使用代码执行 print(opts, args) 时,您会得到:

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

加上冒号后变成:

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

没有冒号 C:\Users\... 成为新参数。