![](/img/trans.png)
[英]Is there anyway to get the names of passed arguments to a function in 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是腳本想要識別的選項字母串,其中的選項需要一個參數后跟冒號(':';即,與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\\...
成為新參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.