0

I am trying to start solr through python script. There are three conditions:

1st when user doesnot provide port number and zookeeper instance.

command : /home/user/solr-5.3.0/bin/solr start

This one works.

2nd when user provides only port number.

command : /home/user/solr-5.3.0/bin/solr start -p 8898

This does not executes.

ERROR: Port number is required when using the -p option!

3rd when user provides both port number and zookeeper instance.

command :/home/user/solr-5.3.0/bin/solr start -p 8898 -z localhost:2181

This also does not executes.

ERROR: Port number is required when using the -p option!

I am new to python scripting. I just need to write scripts for deploying it on servers. Is this the right way of doing it ? Are there any better ways to do it ?

Code

#!/usr/bin/env python


import os
import optparse
import subprocess


parser = optparse.OptionParser()
parser.add_option('-p', dest='port', help='Port(By Default it will start at 8983)',type=int)
parser.add_option('-z', dest='zk', help='zookeeper Server(By default it will take embedded zookeeper)')



(options, args) = parser.parse_args()


if options.port is None and options.zk is None:
subprocess.call(["/home/user/solr-5.3.0/bin/solr start"], shell=True)
elif options.zk is None:
subprocess.call(["/home/user/solr-5.3.0/bin/solr start -p ", str(options.port)], shell=True)
else :
subprocess.call(["/home/user/solr-5.3.0/bin/solr start -p", str(options.port), "-z", str(options.zk)], shell=True)
Ritesh Sinha
  • 820
  • 5
  • 22
  • 50
  • 1
    When you specify `shell=True`, you should just pass an entire string to `subprocess` rather than a list. See answers like [this one](http://stackoverflow.com/questions/25465700/python-subprocess-call-with-shell-false-not-working) for more explanation. – wkl Sep 22 '15 at 13:06

1 Answers1

1

Corrected code:

if options.port is None and options.zk is None:
    subprocess.call(["/home/user/solr-5.3.0/bin/solr", "start"])
elif options.zk is None:
    subprocess.call(["/home/user/solr-5.3.0/bin/solr", "start", "-p", str(options.port)])
else:
    subprocess.call(["/home/user/solr-5.3.0/bin/solr", "start", "-p", str(options.port), "-z", str(options.zk)])
sisoft
  • 953
  • 10
  • 22
  • 1
    `shell=True` is mentioned multiple times in the [subprocess](https://docs.python.org/2/library/subprocess.html) documentation (or [python3's doc](https://docs.python.org/3/library/subprocess.html) if you prefer). – wkl Sep 22 '15 at 12:58
  • ERROR: -p 8898 is not supported by this script – Ritesh Sinha Sep 22 '15 at 13:01
  • @user-4870385, you can try to separate keys and arguments: `subprocess.call(["/home/user/solr-5.3.0/bin/solr", "start", "-p", str(options.port)])` – sisoft Sep 22 '15 at 13:03