gpt4 book ai didi

Python获取传递的参数

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:25 28 4
gpt4 key购买 nike

我正在开发一个项目,该项目允许用户通过添加必要的参数来设置上传文件的路径,但无论出于何种原因,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\... 成为一个新参数。

关于Python获取传递的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37211745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com