【问题标题】:Run python script inside another python script在另一个 python 脚本中运行 python 脚本
【发布时间】:2017-02-28 15:19:01
【问题描述】:

我有一个包含文本预处理功能的脚本“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_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'做任何改变?

谢谢。

【问题讨论】:

  • 在这里尝试使用完整的限定路径:with open('stopwords.txt') as sw:
  • 不要依赖preprocess中的当前工作目录。使用os.path.dirname(os.path.realpath(__file__)) 获取目录并使用该目录查找stopwords.txt
  • 我在这里看到两个问题:1- 问:如何导入不属于同一个Python项目(包)的Python模块? A: 把它放在 pythonpath 中——首选的方法是安装它(create a simple setup.py(或使用cookiecutter 包),运行pip install -e .)。 sys.path.insert() 应避免使用/不使用硬编码路径¶ 2- Q: 如何访问与代码相关的资源(文件)。 答: pkgutil.get_data(), pkg_resources, appdirs

标签: python python-2.7


【解决方案1】:

既然您在类似 *nix 的系统上运行,看来,为什么不使用这个奇妙的环境将您的东西粘合在一起呢?

cat stopwords.txt | python preprocess.py | python process.py

当然,您的脚本应该只使用标准输入,只产生标准输出。看!删除代码并免费获得功能!

【讨论】:

    【解决方案2】:

    最简单,也可能是最明智的方法是传入完整路径的文件名:

    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
    

    那你就可以适当的调用了。

    【讨论】:

    • 我很好奇为什么你会认为这是最明智的方式?如果您移动了一个像这样设置的大型项目,纠正所有完整路径会不会很糟糕?
    • 硬编码的东西让我很担心,我猜想它还没有从其他任何地方被调用,因为问题是关于无法从其他任何地方调用它。
    • 啊,我想我们来自不同的角度。我同意您希望能够将文件名作为参数传递,但如果代码被分成多个目录,我会在 preprocessing.py 内生成目录路径;假设这是一个具有固定结构的项目。我们可能在这方面做了相反的假设。
    【解决方案3】:

    看起来可以放

    import os
    os.chdir('path/to/first/script')
    

    在您的第二个脚本中。请尝试。

    【讨论】:

      【解决方案4】:
      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
      

      【讨论】:

      猜你喜欢
      • 2016-09-03
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      相关资源
      最近更新 更多