且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-24 09:34:33

一个选项:

  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.