Python 获取命令行参数作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37658154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:44:46  来源:igfitidea点击:

Get command line arguments as string

pythoncommand-line-arguments

提问by KocT9H

I want to print all command line arguments as a single string. Example of how I call my script and what I expect to be printed:

我想将所有命令行参数打印为单个字符串。我如何调用我的脚本以及我希望打印的内容的示例:

./RunT.py mytst.tst -c qwerty.c

mytst.tst -c qwerty.c

The code that does that:

这样做的代码:

args = str(sys.argv[1:])
args = args.replace("[","")
args = args.replace("]","")
args = args.replace(",","")
args = args.replace("'","")
print args

I did all replaces because sys.argv[1:] returns this:

我做了所有替换,因为 sys.argv[1:] 返回这个:

['mytst.tst', '-c', 'qwerty.c']

Is there a better way to get same result? I don't like those multiple replace calls

有没有更好的方法来获得相同的结果?我不喜欢那些多次替换调用

回答by cxw

An option:

一个选项:

import sys
' '.join(sys.argv[1:])

The join()function joins its arguments by whatever string you call it on. So ' '.join(...)joins the arguments with single spaces (' ') between them.

join()函数通过您调用它的任何字符串连接其参数。所以' '.join(...)用单个空格 ( ' ')连接参数。

回答by Natesh bhat

The command line arguments are already handled by the shell before they are sent into sys.argv. Therefore, shell quoting and whitespace are gone and cannot be exactly reconstructed.

命令行参数在发送到sys.argv. 因此,shell 引用和空格都消失了,无法完全重建。

Assuming the user double-quotes strings with spaces, here's a python program to reconstruct the command string with those quotes.

假设用户用空格双引号字符串,这里有一个 python 程序用这些引号重建命令字符串。

commandstring = '';  

for arg in sys.argv[1:]:          # skip sys.argv[0] since the question didn't ask for it
    if ' ' in arg:
        commandstring+= '"{}"  '.format(arg) ;   # Put the quotes back in
    else:
        commandstring+="{}  ".format(arg) ;      # Assume no space => no quotes

print(commandstring); 

For example, the command line

例如,命令行

./saferm.py sdkf lsadkf -r sdf -f sdf -fs -s "flksjfksdkfj sdfsdaflkasdf"

will produce the same arguments as output:

将产生与输出相同的参数:

sdkf lsadkf -r sdf -f sdf -fs -s "flksjfksdkfj sdfsdaflkasdf"

since the user indeed double-quoted only arguments with strings.

因为用户确实只用字符串双引号引起来。

回答by szali

None of the previous answers properly escape all possible arguments, like empty args or those containing quotes. The closest you can get with minimal code is to use shlex.quote (available since Python 3.3):

以前的答案都没有正确转义所有可能的参数,例如空参数或包含引号的参数。用最少的代码可以获得的最接近的是使用 shlex.quote (自 Python 3.3 起可用):

import shlex
cmdline = " ".join(map(shlex.quote, sys.argv[1:]))

EDIT

编辑

Here is a Python 2+3 compatible solution:

这是一个 Python 2+3 兼容的解决方案:

import sys

try:
    from shlex import quote as cmd_quote
except ImportError:
    from pipes import quote as cmd_quote

cmdline = " ".join(map(cmd_quote, sys.argv[1:]))

回答by Brice

You're getting a list object with all of your arguments when you use the syntax [1:]which goes from the second argument to the last. You could run a for each loop to join them into one string:

当您使用[1:]从第二个参数到最后一个参数的语法时,您将获得一个包含所有参数的列表对象。您可以为每个循环运行一个将它们连接成一个字符串:

args = sys.argv[1:]
result = ''

for arg in args:
    result += " " + arg