【问题标题】:How to call another python file, run it, and replace main.py with the new .py file?如何调用另一个 python 文件,运行它,并将 main.py 替换为新的 .py 文件?
【发布时间】:2021-05-09 04:37:37
【问题描述】:

有以下问题的答案:

如何从另一个py文件运行一个py文件?

但是没有答案告诉如何用最近运行的文件替换 main.py,但仍然是 jeep main.py。 我使用的是 python 3,我的执行命令是这样的:

exec(open('newfile.py').read())

如何将 main.py 替换为 newfile.py,但保留 main.py?

【问题讨论】:

    标签: python exec


    【解决方案1】:

    对不起!我不清楚您的问题,但我只是尝试像这样创建 first.py:

    first.py

    print('Hello world')
    

    然后像这样制作 second.py:

    second.py

    import os
    os.system('python first.py')
    

    当你想在 CLI 上运行时,你可以输入这个命令 这是我今天文件夹中的环境: 今天文件夹:

    如果不是您的工作或不清楚您的问题,请随时提出更多问题。

    【讨论】:

    • 除此之外,python 的 subprocess 模块代替 os.system 为这些类型的任务提供了更多种类的功能。 docs.python.org/3/library/…
    • @TH_SPT 你好!感谢您的回答,但我正在运行 Discord 机器人,其他用户在 Discord 上时无法在命令行中准确键入命令。希望这是有道理的,再次感谢您的回答!
    • @discord.py_fanboy 欢迎兄弟。你可以让我更多地了解你的不和谐这对我来说是关于不和谐机器人的好习惯。你能邀请我加入你的不和谐,看看和了解它。我只是编程新手,所以我想尝试解决更多问题。随时向我提问。
    【解决方案2】:

    我只是尝试像这样创建 first.py:

    print('hello world!')
    

    还有这样的 second.py:

    import first
    

    那么 first.py 将在 second.py 运行的 Python 环境中运行。 但在 first.py 中,__name__ 的值将是 'first' 而不是 '__main__'

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 2021-10-16
      • 2022-01-02
      • 2013-02-24
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      相关资源
      最近更新 更多