1

I am building a python tool to update an application. To do so i have to stop the apache service, do some update related stuff and then start it again, after the update ist finished.

Im currently using python 3.7.2 on Windows 10.

I have tried to somehow build a working process using these questions as a reference:

Run process as admin with subprocess.run in python

Windows can't find the file on subprocess.call()

Python subprocess call returns "command not found", Terminal executes correctly


def stopApache():
    processName = config["apacheProcess"]
    #stopstr = f'stop-service "{processName}"'
    # the line abpove should be used once im finished, but for testing 
    # purposes im going with the one below
    stopstr = 'stop-service "Apache2.4(x64)"'
    print(stopstr)
    try:
        subprocess.run(stopstr, shell=True)
        #subprocess.run(stopstr)
        # the commented line here is for explanatory purposes, and also to 
        # show where i started.
    except:
        print('subprocess failed', sys.exc_info())
        stopExecution()

From what i have gathered so far, the shell=TRUE option, is a must, since python does not check PATH. Given the nature of what im trying to do, i expected the service to get stoppped. In reality the console error looks like this :

stopstr =  get-service "Apache2.4(x64)"
Der Befehl "get-service" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.

Which roughly translates to : the command "stop-service" is either incorrectly spelled or could not be found.

If i run the same command directly in powershell i get a similar error. If i open the shell as admin, and run i again, everything works fine.

But, if i use the very same admin shell to run the python code, i am back to square one.

What am i missing here, aparently there is some issue with permissions but i cannot wrap my head arround it

jdoe
  • 99
  • 3
  • 14

1 Answers1

2

The command for stopping a service in MS Windows is net stop [servicename]

So change stopstr to 'net stop "Apache2.4(x64)"'

You will need to run your script as admin.

shell=True runs commands against cmd, not powershell.

Powershell is different to the regular command line. So to get stop-service to work you'd have to pass it to an instance of powershell.

stopstr = 'stop-service \\"Apache2.4(x64)\\"'
subprocess.run(['powershell', stopstr], shell=True)

As you noted in a comment, it's neccessary to escape the " around the service name, as first python will unescape them, then powershell will use them.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
  • Just to give heads up for other peaople who read this, to get the powershell to really work, i needed to put things like this : ```stopstr = 'get-service \\"Apache2.4(x64)\\"'``` The double escape is necessary here, because first python will parse this string, and then the powershell will parse it again. – jdoe Jul 19 '19 at 07:08