简体   繁体   English

从另一个文件调用 python function

[英]Calling python function from another file

I am trying to reference a variable from one python file to another.我正在尝试将一个变量从一个 python 文件引用到另一个文件。

I have a base file that has a variable value, current_time and I want to call this variable in another python function that is in another python file.我有一个具有变量值current_time的基本文件,我想在另一个 python function 中调用此变量,该变量位于另一个 python 文件中。

This is what I tried doing:这是我尝试做的:

From the file I am trying to call the variable:从我试图调用变量的文件中:

ref_path = os.path.split(os.getcwd())[0]
ref_path = os.path.join(ref_path, "folder_1", "folder_2", "folder_3")

Now that I am pointing to the destination folder when I try doing现在我在尝试做的时候指向目标文件夹

from ref_path import function as function
 

I am getting an error ModuleNotFoundError: No module named 'ref_path'我收到一个错误ModuleNotFoundError: No module named 'ref_path'

I am trying to call function.current_time我想打电话给function.current_time

Add the path to base file in your syspath and import the variable.在系统路径中添加基本文件的syspath并导入变量。

import sys
sys.path.append(ref_path)

from function import *
# Now you can use the variable

Could you import the file?可以导入文件吗?

assuming the ref path is the directory next to this file you could try this:假设参考路径是这个文件旁边的目录,你可以试试这个:

import os

fullPath = os.path.realpath(__file__)  #this file
thisDir = os.path.dirname(fullPath) # this files directory

from ref_file import ref_module 

print(ref_module.GetCurrentTime())

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

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