Python获取参数
问题描述:
我正在研究一个项目,该项目允许用户通过添加必要参数来设置上传文件的路径,但无论出于何种原因,upload_destination变量始终为空! 这里是我的代码Python获取参数
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
答
这是一个简单的失踪冒号:
调用PROGRAMM。
https://docs.python.org/2/library/getopt.html
选项是选项字母的字符串,脚本要认识到,与那些需要参数后面跟一个冒号(选项“:”,即同一格式的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\...
成为一个新的说法。
+1
非常感谢!这解决了我的问题。 – Aginu
为什么不使用'argparse'(https://docs.python.org/3/library/argparse.html)? – linusg
可能根本不相关,但请尝试使用正斜杠代替。就像如果你有's =“something/new”',它最终会成为's =“something(newline)ew”' – Peter
@Peter我也想到了这一点,所以我试着简单地输入Test和它仍然是空的 – Aginu