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

执行Python脚本遇exec()参数错误,求调用test_function.py函数的解决方法

问题解决方案

错误原因

你遇到的exec() arg 1 must be a string, bytes or code object错误,是因为exec()函数要求传入字符串、字节或代码对象作为参数,但你直接传了一个文件对象file,不符合参数要求。

解决方法

方法一:读取文件内容后执行

修改代码,先读取文件的文本内容,再把内容传给exec():

try:
    from nltk.stem import SnowballStemmer  # 确保导入SnowballStemmer
    stemmer = SnowballStemmer("english")
    with open('test_function.py', 'r') as file:
        sys.stdin = file
        exec(file.read())  # 传入文件内容字符串
    # 这里可以直接调用test_function.py里的函数,比如 your_function()
except Exception as e:
    print(e)

使用with语句能自动关闭文件,避免资源泄漏。

方法二:直接导入模块(更推荐)

如果test_function.py和当前脚本在同一目录下,直接导入模块是更规范、安全的方式,比exec()更易维护:

try:
    from nltk.stem import SnowballStemmer
    stemmer = SnowballStemmer("english")
    import test_function  # 导入test_function模块
    # 调用模块内的函数,格式为 test_function.你的函数名()
    # 比如 test_function.my_test_func()
except Exception as e:
    print(e)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:20:40