2

I want to execute python script by supervisor.

I set up the directory option in supervisord.conf and I used relative path in command option like this.

[supervisord]
http_port=/var/tmp/supervisor.sock ; (default is to run a UNIX domain socket server)
logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;default 10)
loglevel=info               ; (logging level;default info; others: debug,warn)
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false              ; (start in foreground if true;default false)
minfds=1024                 ; (min. avail startup file descriptors;default 1024)
minprocs=200                ; (min. avail process descriptors;default 200)
directory=/root             ; (default is not to cd during start)

[supervisorctl]
serverurl=unix:///var/tmp/supervisor.sock ; use a unix:// URL  for a unix socket

[program:test]
directory=/root/test
command=python ./test.py
autostart=true

In python script, I used relative path like this.

textfile = open('./textfile')

I can successfully execute this python script by python ./test.py on /root/test directory. But when I started supervisor, I got this error.

python: can't open file './test.py': [Errno 2] No such file or directory

Next, I used absolute path in command option of supervisor.conf like this.

[program:test]
directory=/root/test
command=python /root/test/test.py

And I got this error.

Traceback (most recent call last):
  File "/root/test/test.py", line 6, in <module>
    textfile = open('./textfile')
IOError: [Errno 2] No such file or directory: './textfile'

Is there no way to set up the directory on where the script is executed?

nemupm
  • 23
  • 1
  • 4
  • You change `test.py` to change the pwd to that of the script http://stackoverflow.com/questions/1432924/python-change-the-scripts-working-directory-to-the-scripts-own-directory – Ian2thedv Dec 07 '15 at 08:21
  • This seems the easiest way to solve my issue, at least now. Thanks. – nemupm Dec 07 '15 at 13:48

1 Answers1

0

Other than using the absolute path to textfile in test.py, you can change the present working directory to that of the script by adding the following to test.py before calling textfile = open('./textfile'):

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

See python: Change the scripts working directory to the script's own directory

Community
  • 1
  • 1
Ian2thedv
  • 2,691
  • 2
  • 26
  • 47