【发布时间】:2016-09-09 18:05:07
【问题描述】:
我正在开发一个项目,该项目允许用户通过添加必要的参数来设置上传文件的路径,但无论出于何种原因,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
【问题讨论】:
-
为什么不使用
argparse(docs.python.org/3/library/argparse.html)? -
可能根本不相关,但请尝试使用正斜杠。就像如果你有
s = "something/new",它最终会变成s = "something(newline)ew" -
@Peter 我也想到了这一点,所以我通过简单地输入 Test 进行了尝试,它仍然是空的
-
您完全确定
elif块正在执行吗?如果您在upload_destination = a之前的行中添加print("about to change upload destination"),它会被打印出来吗? -
@Kevin 是的,我试过很多次
标签: python command-line-arguments getopt