![](/img/trans.png)
[英]How to access the value of a variable in a python script when executed from another python script using system() command?
[英]How to access a dynamic variable of a Python script from another Python script?
所以有两个脚本: script1.py
和script2.py
。 script1.py
有一个变量x
,用于存储运行时从文件中读取的字符串。 在script2.py
,我导入script1.py
,然后使用以下命令运行script1.py
: script1.main()
。 然后我在script1.py
中运行一个特定的函数,负责读取有问题的文件。
您可能想知道为什么我不首先运行那个特定的函数,而不是运行整个脚本。 那是因为script1.py
每次运行时都会执行script2.py
需要的许多其他事情。
当script1.py
从script2.py
运行时,我希望能够读取x
存储的script2.py
。 我目前所做的基本上是两次运行script1.py
一部分。 我想知道是否可以在不执行以下操作的情况下访问变量x
:
#script1
def read_file():
f = open('file_path.txt')
string = f.read()
return string
def main():
x = read_file()
if __name__ == '__main__':
main()
和script2.py
:
#script2
import script1
from script1 import *
def main():
script1.main()
x = read_file()
print(x)
if __name__ == '__main__':
main()
所以基本上我想知道这种事情通常应该如何完成。 是否可以在不必第二次运行read_file()
的情况下获取x
的值? 当script1.main()
执行时, x
的值存储在哪里以及如何访问它? 不确定我是应该使用import script1
还是应该使用from script1 import *
来实现这一点。
由于x
是script1.main
函数中的局部变量,因此无法从外部访问它(既不能从 script2 也不能从 script1)。 实际上, script1.main
完成后,该对象将被丢弃。 如果要重复使用它,则需要将其存储在其他地方。
一个快速的解决方法是使变量x
全局变量。 然后 script2 可以将其用作script1.x
。
# script1.py
def read_file():
return "foo bar"
def main():
global x
x = read_file()
if __name__ == '__main__':
main()
# script2
import script1
def main():
script1.main()
#x = read_file()
print(script1.x)
if __name__ == '__main__':
main()
如果您不想使用global
语法,另一种方法是在script1.py
定义一个可变变量,并让它存储您要重用的变量。 一种可能性是使用class
。 在这里,我使用class
作为可变存储。 如果您不喜欢它,其他可变对象(例如dict
也可以使用。
# script1.py
class data:
x = None
def read_file():
return "foo bar"
def main():
data.x = read_file()
if __name__ == '__main__':
main()
# script2
import script1
def main():
script1.main()
#x = read_file()
print(script1.data.x)
if __name__ == '__main__':
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.