You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中如何将所有命令行参数合并为单个字符串?

将多个命令行参数合并为单个字符串

方法一:使用sys.argv

直接通过sys.argv获取所有参数,跳过脚本名后用空格连接即可:

import sys

# 跳过第一个元素(脚本文件名),用空格拼接剩余所有参数
combined_string = ' '.join(sys.argv[1:])
print(combined_string)

执行你给出的命令:

python3 p.py first -second and more -and maybe another okay thisisthelast one

会输出:

first -second and more -and maybe another okay thisisthelast one

方法二:使用argparse

如果你已经在使用argparse,可以通过nargs='*'(允许0个或多个参数)或nargs='+'(要求至少1个参数)收集所有位置参数,再拼接成字符串:

import argparse

parser = argparse.ArgumentParser()
# 收集所有位置参数到args列表中
parser.add_argument('args', nargs='*')
args = parser.parse_args()

# 拼接为单个字符串
combined_string = ' '.join(args.args)
print(combined_string)

执行上述命令后,同样会得到你想要的结果。

内容的提问来源于stack exchange,提问作者Døner M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:33:13