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

如何在另一个Python脚本中带指定参数执行Python文件?

在Python脚本中调用main.py并传递参数的正确方法

修复os.system的写法

你之前的代码问题出在字符串格式化未生效,Python不会自动解析普通字符串里的{dog}和{ID},需要用f-string或.format()注入变量:

import os

dog = "dachshund"
ID = 1234
# 方式1:f-string(Python3.6+支持)
os.system(f"python main.py --something-something {dog} --something- {ID}")

# 方式2:.format()兼容旧版本
os.system("python main.py --something-something {} --something- {}".format(dog, ID))

更推荐的方法:使用subprocess模块

os.system功能有限,无法捕获命令输出、错误信息,也难处理复杂场景。Python官方推荐用subprocess模块,它更灵活、安全:

方式1:类似os.system的shell调用(简单但需注意安全)

import subprocess

dog = "dachshund"
ID = 1234
# shell=True让系统shell解析整条命令,和os.system逻辑一致
# check=True会在命令执行失败时抛出异常,方便排查问题
subprocess.run(f"python main.py --something-something {dog} --something- {ID}", shell=True, check=True)

方式2:无shell调用(更安全,推荐)

当参数包含特殊字符(比如空格、引号)时,shell解析可能出错,建议把命令拆成列表传递,避免shell注入风险:

import subprocess

dog = "dachshund"
ID = 1234
# 每个命令/参数单独作为列表元素,整数ID要转成字符串
subprocess.run(
    ["python", "main.py", "--something-something", dog, "--something-", str(ID)],
    check=True
)

如果需要捕获main.py的输出或错误,可以添加capture_output=True参数:

result = subprocess.run(
    ["python", "main.py", "--something-something", dog, "--something-", str(ID)],
    check=True,
    capture_output=True,
    text=True
)
# 打印输出
print(result.stdout)
# 打印错误(如果有)
print(result.stderr)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:05:18