调用 PyPI 包中的其他脚本

Calling other scripts in PyPI package

我有一个 Python 包,我已经上传到 PyPP。该脚本将另外两个 R 脚本调用到 运行。我已验证所需的 R 脚本也已上传到 PyPI(通过实际下载最新版本并在目录中查看它们)。我也可以成功安装 运行 主 python 脚本。

但是,我无法弄清楚如何从 Python 脚本中调用 R 脚本。也就是说,我使用什么目录结构?这是我用来 运行:

的命令
$ python_script -f file1.txt -g file2.txt

我得到这个错误:

Fatal error: cannot open file 'script.r': No such file or directory

在 Python 脚本中,我调用 R 脚本的方式如下:

cmd = [ 'Rscript', 'python_script/Rscript.r' ]
    output = subprocess.Popen(cmd, stderr=subprocess.PIPE).communicate()
    result = output[1].decode('utf-8')

但我尝试的任何东西都不起作用:我只尝试了 'Rscript.r' 和 './Rscript.r'

我不知道如何正确调用这个脚本。它和主目录在同一个目录 python_script 我是 运行ning.

此处的路径是相对于您从中调用 python_script 的路径,但是您的 R 脚本存在于相对于您的软件包安装位置的目录中。

您可以使用__file__ 来确定正在执行的文件的完整路径。通过拆分它,您可以获得安装包的目录的路径,然后添加任何额外的 directories/filenames 以获得 R 脚本的完整路径:

import os
this_dir, this_filename = os.path.split(__file__)
RSCRIPT_PATH = os.path.join(this_dir, "Rscript.r")
cmd = ['Rscript', RSCRIPT_PATH]
output = subprocess.Popen(cmd, stderr=subprocess.PIPE).communicate()
result = output[1].decode('utf-8')

注意:此处确保跨平台兼容性的最佳做法是使用os.path.join('path', 'to', 'file.txt')生成路径而不是path/to/file.txt,因为并非所有平台使用 / 作为路径分隔符。