简体   繁体   English

从另一个文件导入变量以在python中运行

[英]import variables from another file to function in python

variables.py variables.py

path="c:/something"
path2="c:/somethng2"
path3="c:/something3"
....

main.py main.py

def run():
    from variables import *

...

i have such error: 我有这样的错误:

SyntaxError: import * is not allowed in function 'run' because it contains a nested function with free variables SyntaxError:函数'run'中不允许import *,因为它包含带有自由变量的嵌套函数

import variables as v
path=v.path

This should do for path variable from other file 这应该从其他文件的路径变量
Hope this helps! 希望这可以帮助!

You should be very careful with global variables. 你应该非常小心全局变量。 It is considered a better practice to avoid using global variables, updating them in different locations in the code. 避免使用全局变量,在代码中的不同位置更新它们被认为是更好的做法。 It should not be a problem if those are only constants, though. 但是,如果那些只是常数,那应该不是问题。 Usually I do it this way: 通常我会这样做:

variables.py : variables.py

MY_PATH1 ="c:/something"
MY_PATH2 ="c:/somethng2"
MY_PATH3 ="c:/something3"

main.py main.py

from variables import *

def run():
    print(MY_PATH1)
    ...

If you are working with path strings, you may also want to take a look in the documentation for the os.path module. 如果您正在使用路径字符串,您可能还需要查看os.path模块的文档 It helps making path descriptors compatible with the different platforms, among other useful things. 它有助于使路径描述符与不同平台兼容,以及其他有用的东西。

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

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