在另一个python脚本中运行python脚本
我有一个脚本'preprocessing.py',包含文本预处理函数:在另一个python脚本中运行python脚本,python,python-2.7,Python,Python 2.7,我有一个脚本'preprocessing.py',包含文本预处理函数: def preprocess(): #...some code here with open('stopwords.txt') as sw: for line in sw.readlines(): stop_words.add(something) #...some more code than doesn't matter return stop_wo
def preprocess():
#...some code here
with open('stopwords.txt') as sw:
for line in sw.readlines():
stop_words.add(something)
#...some more code than doesn't matter
return stop_words
现在我想在另一个Python脚本中使用这个函数。
因此,我做了以下工作:
import sys
sys.path.insert(0, '/path/to/first/script')
from preprocessing import preprocess
x = preprocess(my_text)
最后,我提出了一个问题:
IOError: [Errno 2] No such file or directory: 'stopwords.txt'
问题肯定是“stopwords.txt”文件位于第一个脚本的旁边,而不是第二个脚本
是否有任何方法可以指定此文件的路径,而不对脚本“preprocessing.py”进行任何更改
谢谢。最简单、可能也是最合理的方法是传入完全路径文件名:
def preprocess(filename):
#...some code here
with open(filename) as sw:
for line in sw.readlines():
stop_words.add(something)
#...some more code than doesn't matter
return stop_words
然后您可以适当地调用它。看起来您可以
import os
os.chdir('path/to/first/script')
在第二个脚本中。请试一试。既然你是在一个*nix系统上运行的,那么为什么不使用这个奇妙的环境将你的东西粘在一起呢
import os
def preprocess():
#...some code here
# get path in same dir
path = os.path.splitext(__file__)
# join them with file name
file_id = os.path.join(path, "stopwords.txt")
with open(file_id) as sw:
for line in sw.readlines():
stop_words.add(something)
#...some more code than doesn't matter
return stop_words
cat stopwords.txt | python preprocess.py | python process.py
当然,您的脚本应该只使用标准输入,而只生成标准输出。看见删除代码并免费获得功能 在此处尝试使用完整的限定路径:
打开('stopwords.txt')作为sw:
不要依赖于预处理中的当前工作目录。使用os.path.dirname(os.path.realpath(\uuu file\uuu))
获取目录,并使用该目录查找stopwords.txt
。我在这里看到两个问题:1-Q:如何导入不属于同一Python项目(包)的Python模块?答:把它放在pythonpath中——首选的方法是安装它(或者使用cookiecutter
package),运行pip安装-e.
)<代码>sys.path.insert()
应避免使用/不使用硬编码路径»2-Q:如何访问与代码相关的资源(文件)。答:我很好奇为什么你会认为这是最明智的方法?如果你移动了一个像这样设置的大型项目,那么纠正所有完整的路径不是很可怕吗?硬编码的东西让我感到困惑,我猜它不会从任何其他地方调用,因为问题是无法从任何其他地方调用它。啊,我想我们来自不同的角度。我同意您希望能够将文件名作为参数传递,但如果代码被分成多个目录,我会在preprocessing.py
中生成目录路径;假设这是一个固定结构的项目。我们可能在这方面做了相反的假设。1-splitext()
似乎不正确。你可能意味着代替2——而不是手动定位文件,例如