我正在开发一个项目,允许用户通过添加必要的参数来设置上传文件的路径,但无论出于何种原因,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
答案 0 :(得分:7)
这是一个简单的缺少冒号:
。
https://docs.python.org/2/library/getopt.html
options是脚本想要识别的选项字母串,其中的选项需要一个后跟冒号的参数(':';即,与Unix getopt()使用的格式相同)。
将"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\...
成为新的参数。