2016-05-13 5 views
3

私は、ユーザーが必要な引数を追加することによってファイルをアップロードするためのパスを設定できるプロジェクトに取り組んでいますが、何らかの理由でupload_destination変数は常に空です! は、ここで私はそれは、単純な行方不明コロン:Python get passed passed arguments

C:\Users\Asus\Desktop\PythonTest>python test.py -l -c -p 3500 -u C:\Users\Asus\Desktop\Test 
+2

なぜ 'argparse'(https://docs.python.org/3/library/argparse.html)を使用しないのですか? – linusg

+0

まったく関連していない可能性がありますが、代わりにスラッシュを使用してみてください。 's =" something/new "'を持っていたように、 's =" something(newline)ew "' – Peter

+0

@Peterでも考えました。まだ空だった – Aginu

答えて

7

を入力することにより、プログラムの開発を呼び出す私のコード

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() 

です。

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']) 

それはなっ追加コロンコロンC:\Users\...なし

([('-l', ''), ('-c', ''), ('-p', '3500'), ('-u', 'C:UsersAsusDesktopTest')], []) 

は新しい引数になります。

+1

ありがとうございました!これは私の問題を解決しました。 – Aginu