简体   繁体   English

Python 新手关于导入本地依赖的问题

[英]Python Newbie question about importing local dependency

How do you call a python script to be used in another python script?如何调用 python 脚本以用于另一个 python 脚本?

This is my folder structure:这是我的文件夹结构:

\>Process_Sypht(root folder)
 \>Sypht_Scripts(subfolder)
 \>Python_Lib_Script(subfolder)

Scripts from Sypht_Script invoke scripts in Python_Lib_Script . Sypht_Script中的脚本调用Python_Lib_Script中的脚本。

One example being called by Sypht_Toolbox (inside Sypht_Scripts ) is this script: sypht_var (inside Python_Lib_Script ). Sypht_Toolbox (在Sypht_Scripts内)调用的一个示例是这个脚本: sypht_var (在Python_Lib_Script内)。 Now inside the script, here's how I tried to import sypht_var现在在脚本中,这是我尝试导入sypht_var的方式

链接因为我还不能附加图片

Unfortunately this doesn't work, how can I improve this?不幸的是,这不起作用,我该如何改进?

The easiest way of doing it is to have both python scripts in the same folder, then you can import it normally with no need for using sys.path最简单的方法是将两个 python 脚本放在同一个文件夹中,然后您可以正常导入它而无需使用 sys.path

Your question wasn't that clear on whether you want to do it from Sypht_toolbox to sypht_var so here i did this from the Syphy_Toolbox to Sypht_var so it would be the same as for other way around as well你的问题不是很清楚你是否想从 Sypht_toolbox 到 sypht_var 所以在这里我从 Syphy_Toolbox 到 Sypht_var 这样做了,所以它也与其他方式相同

Sypht_var.py sypht_var.py

#I am just passing a single variable for testing
name="testing"

Syphy_Toolbox.py Syphy_Toolbox.py

import sys
import os

#moves a step back
os.chdir('..');

#Setting up the path before passing to sys.path.insert
something = os.path.join(os.getcwd()+'\Python_Lib_Script')

sys.path.insert(0,something)
print(sys.path[0])
from sypht_var import name
print(name)

instead of going with sys.path[0] try with the os model as it works best for with the operating system that you be using.而不是使用 sys.path[0] 尝试使用 os model,因为它最适合您使用的操作系统。

I hope this answer resolves your issue.我希望这个答案能解决你的问题。

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

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