繁体   English   中英

Python3-使用用户输入在另一个python文件中覆盖变量值

[英]Python3 - Overwrite variable value in another python file using user input

我目前正在尝试写入另一个python文件,以使用用户输入替换变量。

假设我有file_a.py和file_b.py

我想执行文件b,以从文件a中获取变量。 然后将该用户输入值保存到file_a.py中的var1中。

例:

file_a.py内容:

var1 = "/path/to/file"

file_b.py内容:

print(var1 " is the current path") 

userinput = input("Type new directory path here: ")

如果两个文件都在同一文件夹中,则可以:

file_b.py

from file_a import var1

print(var1 " is the current path")

userinput = input("Type new directory path here: ")

var1 = userinput

要么

import file_a

print(file_a.var1 " is the current path")

userinput = input("Type new directory path here: ")

file_a.var1 = userinput

但是,您知道您不能修改另一个文件本身吗? var1将在内存中更改,但是如果打开file_a.py ,则var1将为“ / path / to / file”。

PS:一点建议print(var1 " is the current path") -> print(var1, "is the current path")

编辑:我认为从您的水平来看这将是一件好事(您正在做功课,例如,如果我做得更有效,或者有了一些模块,老师会注意到的)。

def re_write(new):
    with open("file_a.py", 'r') as file:
        new_file = []
        for line in file:
            if "var1" in line:
                new_file.append(line.split("var1")[0] + "var1 = '" + new + "'")
            else:
                new_file.append(line)
        with open("file_a.py", 'w') as file:
            for line in new_file:
                file.writelines(line)

这个问题中可以找到更好的代码(更快,内存使用更少,也许总体上更好)。

您是否要编辑file_a.py的文本? 如果是这样,那么您可以查看软件包redbarron 如果要将file_a作为模块导入,则可以这样编辑其全局变量:

import file_a file_a.var1 = 'new value'

这称为“猴子修补”,并且效果将一直存在,直到程序退出。 下次执行该操作将无效。

但是,我觉得这个问题可能被误导了。 请问您要完成什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM