Full command line as it was typed

后端 未结 8 2092
猫巷女王i
猫巷女王i 2020-12-01 20:56

I want to get the full command line as it was typed.

This:

\" \".join(sys.argv[:])

doesn\'t work here (deletes double quotes). Also I pr

8条回答
  •  情书的邮戳
    2020-12-01 21:31

    I am just 10.5 years late to the party, but... here it goes how I have handled exactly the same issue as the OP, under Linux (as others have said, in Windows that info may be possible to retrieve from the system).

    First, note that I use the argparse module to parse passed parameters. Also, parameters then are assumed to be passed either as --parname=2, --parname="text", -p2 or -p"text".

    call = ""
    for arg in sys.argv:
        if arg[:2] == "--": #case1: longer parameter with value assignment
            before = arg[:arg.find("=")+1]
            after = arg[arg.find("=")+1:]
            parAssignment = True
        elif arg[0] == "-": #case2: shorter parameter with value assignment
            before = arg[:2]
            after = arg[2:]
            parAssignment = True
        else: #case3: #parameter with no value assignment
            parAssignment = False
        if parAssignment:
            try: #check if assigned value is "numeric"
                complex(after) # works for int, long, float and complex
                call += arg + " "
            except ValueError:
                call += before + '"' + after + '" '
        else:
            call += arg + " "
    

    It may not fully cover all corner cases, but it has served me well (it can even detect that a number like 1e-06 does not need quotes).

    In the above, for checking whether value passed to a parameter is "numeric", I steal from this pretty clever answer.

提交回复
热议问题