获取命令行参数作为字符串 [英] Get command line arguments as string
本文介绍了获取命令行参数作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将所有命令行参数打印为单个字符串。我如何调用脚本以及如何打印脚本的示例:
./ RunT.py mytst.tst -c qwerty .c
mytst.tst -c qwerty.c
这样做:
args = str(sys.argv [1:])
args = args.replace( [,)
args = args.replace(,)
args = args.replace(,,)
args = args.replace( ',)
print args
我都做了替换,因为sys.argv [1:]返回以下内容:
['mytst.tst','-c','qwerty.c']
是否有更好的方法来获得相同的结果?我不喜欢这些多个替换调用
解决方案
一个选项:
import sys
''.join(sys.argv [1:])
join()
函数通过您调用的任何字符串将其参数连接起来。因此''.join(...)
将参数之间用单个空格(''
)连接。 / p>
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:
['mytst.tst', '-c', 'qwerty.c']
Is there a better way to get same result? I don't like those multiple replace calls
解决方案
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.
这篇关于获取命令行参数作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文