Lukas
Lukas

Reputation: 2352

Why running python script causes an error in Apache

Running the following python script through web site works fine and (as expected) stops the playback of MPD:

#!/usr/bin/env python
import subprocess
subprocess.call(["mpc", "stop"])
print ("Content-type: text/plain;charset=utf-8\n\n")
print("Hello") 

This script however causes an error (playback starts as expected):

#!/usr/bin/env python
print("Content-type: text/plain;charset=utf-8\n\n")
print ("Hello")

import subprocess
subprocess.call(["mpc", "play"])

The error is:

malformed header from script. Bad header=Scorpions - Eye of the tiger -: play.py, referer: http://...

Apparently whatever is returned by the playback command is taken as the header. When run in terminal, the output looks fine. Why could it be?

Upvotes: 0

Views: 1944

Answers (2)

Blender
Blender

Reputation: 298106

  1. You're running your script in some sort of CGI-like environment. I would strongly suggest using a light web framework like Flask or Bottle.
  2. mpc play is writing to stdout. You need to silence it:

    import os
    
    with open(os.devnull, 'w') as dev_null:
        subprocess.call(["mpc", "stop"], stdout=dev_null)
    
  3. For your HTTP headers to be valid, you need to separate them with \r\n, not \n\n.

Upvotes: 2

user823738
user823738

Reputation: 17521

You need to use \r\n line endings.

Upvotes: 0

Related Questions