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

如何在os.system()命令中使用多个变量与字符串?

解决命令拼接问题

你的代码里字符串拼接的写法错误,str()函数无法接受多个参数,这会直接抛出TypeError。下面是几种正确的实现方式:

方法1:字符串加号拼接

直接用+把各部分字符串连起来:

cmd = "curl " + url + " --output " + filename
os.system(cmd)

方法2:f-string格式化(推荐)

Python3.6及以上版本支持的f-string,写法更简洁直观:

cmd = f"curl {url} --output {filename}"
os.system(cmd)

方法3:str.format()格式化

兼容性更好的格式化方式,适合低版本Python:

cmd = "curl {} --output {}".format(url, filename)
os.system(cmd)

更安全的替代方案

用os.system()存在命令注入风险(比如用户输入的URL或文件名包含特殊字符),推荐使用subprocess模块,直接传递参数列表,不需要拼接字符串:

import subprocess

# 收集用户输入部分不变
print("hello! welcome to the website dowloader! paste in the url(including the http part) and type in the file name!")
url = input("website url: ")
filename = input("the filename:")

# 用subprocess.run执行命令
subprocess.run(["curl", url, "--output", filename], check=True)

这种方式会自动处理参数中的特殊字符,避免安全问题,同时能更好地捕获命令执行的状态。

内容的提问来源于stack exchange,提问作者elapt1c alt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:35:30