【问题标题】:writing and then running a python file using python使用python编写然后运行python文件
【发布时间】:2022-01-15 02:55:54
【问题描述】:

我在一个文件(假设 file_0.py)中编写了一个 python 代码,我正在其中编写一个具有递增索引的 python 文件(如 file_1.py)。索引被读取并保存在 index.txt 文件中,并在整个代码中递增。

import os
def write_fun_and_call():
    with open(__file__, 'r') as current_file:
        fun_str = current_file.read()
    with open("index.txt", 'r') as init_file:
        i = int(init_file.read())
    i += 1
    with open("index.txt", 'w') as init_file:
        init_file.write(str(i))

    python_file = "fun_" + str(i) + ".py"
    with open(python_file, 'w') as pyFile:
        pyFile.write(fun_str)
    # os.system("python " + python_file)
    return

write_fun_and_call()

我的问题是“如果我取消注释该行(os.system)并运行代码,它是否安全,或者会出现某种内存问题,如果我可以控制索引会发生什么,在这种情况下是没关系 ?” 提前致谢。

【问题讨论】:

  • exec 是更好的方法,如果这样做,将文件中的字符串读入 python 字符串变量,然后调用 exec(var)
  • 这完全取决于输入文件中的内容;但一般来说,不,你不能保证文件中没有任何不好的东西,你应该只执行你审计过的代码。无论如何,这似乎是每个可以想象的问题陈述的糟糕解决方案,非常像XY Problem;您实际上希望在这里实现什么?
  • 由于所有先前启动的进程都保留在内存中或移动到(也是有限的)页面文件中,如果您没有足够早地停止,则会出现内存问题。
  • 这里的代码看起来很复杂,你也许可以实现“不是明显不安全”但不是“明显不安全”。您的问题描述似乎相当模糊,但我会含糊地建议寻找 Python 沙箱或在 Python 之上实现自己的虚拟机架构,您可以更直接地控制生成的代码可以访问和修改的内容。
  • @GautamJangid 故障前可能的精确代数取决于操作系统的其他活动,因此会发生变化且不可预测。

标签: python python-3.x string file command


【解决方案1】:

不,如果应用程序在后台运行是不安全的,- 停止 ull 必须执行其他操作。如果你从控制台运行它,你可以按 ctrl+c 停止。

import os
def write_fun_and_call():
    with open(__file__, 'r') as current_file:
        fun_str = current_file.read()
    with open("index.txt", 'r+') as init_file:
        i = int(init_file.read())
        i += 1
        init_file.seek(0)
        init_file.write(str(i))
        print(i)
    if i>=10: #emergency stop
        exit()        

    python_file = "fun_" + str(i) + ".py"
    with open(python_file, 'w') as pyFile:
        pyFile.write(fun_str)
    os.system("python " + python_file) #os.system(python_file) if python in systempath
    return i


print(write_fun_and_call())
'''
1
2
3
4
5
6
7
8
9
10
9
8
7
6
5
4
3
2
1
'''

第一个应用程序将最后停止

【讨论】:

  • 你有没有通过删除评论(os.system)检查它?
  • 是的,但我添加if i>=10: exit(); 停止,如果我删除它,我也可以在终端中通过 ctrl+c 停止应用程序。对于真正的“不安全”需要使用os.system('at ...
  • 你刚刚停止了代码,条件为 i=10;这不是我要问的,我实际上是在问代码是否可以无限运行,我们可以管理代码以控制它占用大内存(通过 RAM 或存储),并且可以放置一些特定的逻辑来检查行为.例如我们可以删除旧的索引文件,控制 i 的增量值等。
  • 是的,但它需要调用操作系统函数。 os.system("start " + python_file) 适用于 windows & 有紧急停止的方法 - 删除 'index.txt' 我们会有例外
  • 是的,使用os.system("start /B " + python_file)
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
相关资源
最近更新 更多