【问题标题】:Set working directory in Python / Spyder so that it's reproducible在 Python / Spyder 中设置工作目录,使其可重现
【发布时间】:2016-11-18 12:25:11
【问题描述】:

来自 R,使用 setwd 更改目录是对可重复性的一个很大的禁忌,因为其他人没有与我相同的目录结构。因此,建议使用脚本所在位置的相对路径。

IDE 会稍微复杂一点,因为它们设置了自己的工作目录。在 Rstudio 中,我可以通过 Rstudio 的项目轻松解决这个问题,将项目的目录设置为我的脚本文件夹。

对于 Python 和 Spyder,似乎没有任何解决方案。 Spyder 没有像 Rstudio 的项目那样的功能。 Setting the directory to the script's location 在进行交互式分析时不起作用(因为 __file__ 不可用)。

如何使 Python/Spyder 中的工作目录可重现?

【问题讨论】:

  • 这些答案都不像 R 库 "here" 那样开始工作。
  • 一个没有将默认目录与脚本目录相关联的 IDE,如果尚未保存脚本,则不会与用户目录相关联,这在 2016 年是相当奇怪的。不幸的是,Spyder 仍然属于5年后这个类别。在 Python 世界中,c 常数以 km/h 而不是 Gm/s 表示;-)

标签: python spyder reproducible-research


【解决方案1】:

根据这个 GitHub 票证,他们似乎确实认为这是 Spyder 中的一项功能,但截至 5 月中旬,它仍在等待实施:

我们可以在“运行”对话框中添加一个选项来自动设置 工作目录到您的脚本正在运行的目录。

但是,其他人将不得不实施它。我们很忙 暂时还有其他事情,抱歉。

https://github.com/spyder-ide/spyder/issues/3154

@ccordoba12 ccordoba12 于 5 月 14 日将此添加到愿望清单里程碑

【讨论】:

  • 该问题仍未解决。它已经以不同的方式解决了。看看@AkashMantry 的回答。
【解决方案2】:

在此期间,您可以使用 os.chdir

import os
os.chdir('C:\Users\me\Documents')

【讨论】:

    【解决方案3】:

    要自动执行此操作,请将其放在脚本的开头:

    from os import chdir, getcwd
    wd=getcwd()
    chdir(wd)
    

    【讨论】:

    • 这似乎不再起作用了。 wd Out[4]: 'C:\\Users\\Admin' 虽然我运行代码的 .py 文件位于不同的目录中。通常,如果您使用 F5 运行脚本,则会正确分配目录,请参阅github.com/spyder-ide/spyder/issues/3154,请参阅@Hack-R 的答案。
    【解决方案4】:

    嗯,有很多事情你可以尝试! 1. 将目录更改为工具栏中的当前目录。 2. 将 Global 目录更改为 Preferences>Global Working Directory 中的当前目录。单击“当前文件目录”单选按钮。

    希望对你有帮助!

    【讨论】:

      【解决方案5】:

      我试过了,效果很好。

      import os
      abspath = os.path.abspath('') ## String which contains absolute path to the script file
      os.chdir(abspath) ## Setting up working directory
      

      【讨论】:

      • 这似乎不再起作用了。 os.path.abspath('') Out[12]: 'C:\\Users\\Admin' 虽然我运行代码的 .py 文件位于不同的目录中。通常,如果您使用 F5 运行脚本,则会正确分配目录,请参阅github.com/spyder-ide/spyder/issues/3154,请参阅@Hack-R 的答案。
      【解决方案6】:

      正如我写的 here,Mark8888 pointed out 运行整个脚本(运行文件 (F5))而不是脚本的片段

      这种方式应该可以使用多种方法来获取脚本文件位置并更改当前工作目录

      import os
      # directory of script file
      print(os.path.abspath(os.path.dirname(__file__)))
      # change current working directory
      os.chdir(os.path.abspath(os.path.dirname(__file__)))
      # current working directory
      print(os.getcwd())
      

      还有

      import os
      import sys
      # directory of script file
      print(os.path.abspath(os.path.dirname(sys.argv[0])))
      # change current working directory
      os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
      # current working directory
      print(os.getcwd())
      

      【讨论】:

        猜你喜欢
        • 2018-06-03
        • 2017-03-01
        • 1970-01-01
        • 2017-02-15
        • 2018-03-21
        • 2018-08-27
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多