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

时间:2017-12-07 03:46:59

标签: python python-3.x input

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

假设我有file_a.py和file_b.py

我想执行文件b从文件a中获取变量。然后将该userinput值保存到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: ")

2 个答案:

答案 0 :(得分:1)

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

<强> 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将为&#34; / path / to / file&#34;。

P.S:一点建议print(var1 " is the current path") - &gt; 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)

this question中可以找到更好的代码(更快,内存使用量更少,可能更好)。

答案 1 :(得分:1)

您是否正在尝试编辑const path = require('path') const webpack = require('webpack') const namedModules = new webpack.NamedModulesPlugin(); const hotModuleReplacement = new webpack.HotModuleReplacementPlugin(); const config = { context: path.resolve(__dirname, 'src'), entry: './index.jsx', devtool: 'eval-source-map', output: { path: path.resolve(__dirname, 'dist'), publicPath: '/', filename: 'bundle.js' }, module: { rules: [{ test: /\.(js|jsx)$/, include: path.resolve(__dirname, 'src'), use: [{ loader: 'babel-loader', options: { presets: [ ['env', {'es2015': {'modules': false}}], 'react' ], plugins: [ 'transform-object-rest-spread', ] } }] }] }, resolve: { extensions: ['.js', '.jsx', '.json', '*'], modules: [ 'node_modules' ] }, plugins: [ namedModules, hotModuleReplacement ], devServer: { port: 9000, host: 'localhost', inline: true, hot: true } } module.exports = config 的文字?如果是这样,那么您可以查看包file_a.py。如果要将file_a导入为模块,则可以编辑其全局变量:

redbarron

这被称为&#34;猴子补丁&#34;并且效果将在程序退出之前就位。下次执行它将无效。

然而,我觉得这个问题很可能是错误的。我可以问你想要完成什么吗?