9

我正在分发一个具有这种结构的包:

mymodule:
  mymodule/__init__.py
  mymodule/code.py
  scripts/script1.py
  scripts/script2.py

mymodule子目录mymodule包含代码,scripts子目录包含应该由用户执行的脚本。

在描述包安装时setup.py,我使用:

scripts=['myscripts/script1.py']

指定脚本应该去哪里。在安装过程中,它们通常进入某个平台/用户特定的bin目录。我拥有的代码mymodule/mymodule需要调用脚本。然后找到这些脚本的完整路径的正确方法是什么?理想情况下,它们此时应该在用户的路径上,所以如果我想从 shell 中调用它们,我应该能够:

os.system('script1.py args')

但我想通过它的绝对路径调用脚本,而不是依赖于平台特定的 bin 目录在 上PATH,如:

# get the directory where the scripts reside in current installation
scripts_dir = get_scripts_dir()
script1_path = os.path.join(scripts_dir, "script1.py")
os.system("%s args" %(script1_path))

如何才能做到这一点?谢谢。

编辑删除脚本之外的代码对我来说不是一个实用的解决方案。原因是我将作业分配到集群系统,而我通常这样做的方式是这样的:假设您有一组要运行的任务。我有一个脚本,它将所有任务作为输入,然后调用另一个脚本,该脚本仅在给定任务上运行。就像是:

main.py:
for task in tasks:
  cmd = "python script.py %s" %(task)
  execute_on_system(cmd)

所以main.py需要知道在哪里script.py,因为它需要是一个可执行的命令execute_on_system

4

3 回答 3

3

我认为你应该构建你的代码,这样你就不需要从你的代码中调用脚本。将您需要的代码从脚本移动到包中,然后您可以从脚本和代码中调用此代码。

于 2012-10-20T10:49:01.637 回答
1

我的用例是检查我的脚本安装到的目录是否在用户的路径中,如果不是,则发出警告(因为如果使用 --user 安装,它通常不在路径中)。这是我想出的解决方案:

from setuptools.command.easy_install import easy_install

class my_easy_install( easy_install ):

    # Match the call signature of the easy_install version.
    def write_script(self, script_name, contents, mode="t", *ignored):

        # Run the normal version
        easy_install.write_script(self, script_name, contents, mode, *ignored)

        # Save the script install directory in the distribution object.
        # This is the same thing that is returned by the setup function.
        self.distribution.script_install_dir = self.script_dir

...

dist = setup(...,
             cmdclass = {'build_ext': my_builder,  # I also have one of these.
                         'easy_install': my_easy_install,
                        },
            )

if dist.script_install_dir not in os.environ['PATH'].split(':'):
    # Give a sensible warning message...

我应该指出,这是针对 setuptools 的。如果使用 distutils,则解决方案类似,但略有不同:

from distutils.command.install_scripts import install_scripts

class my_install_scripts( install_scripts ):  # For distutils
    def run(self):
        install_scripts.run(self)
        self.distribution.script_install_dir = self.install_dir

dist = setup(...,
             cmdclass = {'build_ext': my_builder,
                         'install_scripts': my_install_scripts,
                        },
            )
于 2015-11-05T17:13:55.013 回答
1

我认为正确的解决方案是

scripts=glob("myscripts/*.py"),
于 2021-08-11T08:56:09.520 回答