如何从另一个文件中打印在Python中的变量
我有第一个文件是:test.py:
age_var = 22
def first_code():
var1 = 'phone'
var2= 'name'
var3= 'last_name'
there are more code down ...........
在第二个文件中,我只想打印var1和age_var,在test2.py文件中:
from dir.test import *
print(var1)
print(age_var)
我该怎么做?
I have tow files the first one is: test.py:
age_var = 22
def first_code():
var1 = 'phone'
var2= 'name'
var3= 'last_name'
there are more code down ...........
In the second one I Want to print var1 and age_var only, in the test2.py file:
from dir.test import *
print(var1)
print(age_var)
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
var1
是在first_code
中定义的,因此您需要拥有该函数返回var1
,然后 call 来自另一个模块的函数,以便var1
将被定义然后返回。Since
var1
is defined insidefirst_code
, you'll need to have that functionreturn var1
, and then call the function from the other module so thatvar1
will get defined and then returned.您需要使所有要在该功能之外使用的变量全局使用,可以通过执行此操作
,然后通过执行test.py文件将其导入到test2.py
中test和test2在不同的目录中,首先确保具有test.py的dir具有一个称为
__ init __. py
此文件可以为空的文件下一个这样的导入,因此在您的情况下,
请记住将
directory.name
更改为您的目录替换所有/s with .s
希望这有帮助:)
you need to make all the variables global that you want to use outside of that function you can do that by doing
and then import the test.py file into test2.py by doing this if test and test2 are in the same dir
do this if test and test2 are in different directories, first make sure that the dir that has test.py has a file called
__init__.py
this file can be empty, this is so python know that that dir is a package next import it like thisso in your case
remember to change
directory.name
to your directory replacing all the/s with .s
hope this helps :)