0

我有一个在相对目录中查找文件的 python 脚本。例如:python 脚本在/home/username/projectname/. 我有一个在/home/username/projectname/subfolder.

如果我从 shell 运行脚本,因为python scriptname.py它运行得很好。

但是,我正在尝试将脚本作为启动服务运行。我在 webmin 中设置它,我相信它使用终端命令来调用它。在启动命令中,我正在做这样的事情来调用脚本:

execute python home/username/projectname/scriptname.py. 该脚本启动正常,但我收到错误,因为它无法访问相对目录中的文件。

我猜有一种更好的方法可以从启动命令中调用 python 程序,以便它知道相对路径。

4

3 回答 3

3
import os

os.chdir("/tmp")

也有:

os.getcwd()

也许您需要以下内容?

import os.path

dir = os.path.dirname(__file__)
于 2012-07-09T00:12:30.373 回答
1

__file__是用于运行脚本的路径。

将其复制到脚本文件中并尝试运行它:

import os

print "This script was run as: %r" % __file__
print "This script is: %r" % os.path.abspath(__file__)

script_dir = os.path.dirname(os.path.abspath(__file__))
print "This script is in directory: %r" % script_dir

print "When started, the current directory was: %r" % os.getcwd()

os.chdir(script_dir)
print "After calling os.chdir(), the current directory is: %r" % os.getcwd()
于 2012-07-09T00:19:48.433 回答
1

启动 python 脚本(可能是 forkink)的进程有一个 pwd(它的工作目录)。这个想法是在fork和执行python之前更改进程的pwd。

您需要查看执行 shell 命令的进程的手册,并了解如何设置 pwd。(在 shell 中您使用 cd 或 pushd)

于 2012-07-09T00:06:12.360 回答