问题
I am trying to build a very simple python script to automate minifying/combining some css/js assets.
I am not sure how to properly handle the minification step. I use yui-compressor and usually call the jar directly from the command line.
Assuming the build script is in the same directory as rhino js.jar
and yui-compressor.jar
, I'd be able to compress a css/js file like so:
java -cp js.jar -jar yuicompressor-2.4.4.jar -o css/foo.min.css css/foo.css
Calling that from the terminal works fine, but in the python build file, it does not
eg, os.system("...")
The exit status being returned is 0
, and no output is being returned from the command (for example, when using os.popen()
instead of os.system()
)
I'm guessing it has something to do with paths, perhaps with java not resolving properly when calling to os.system()
… any ideas?
Thanks for any help
回答1:
I have a somewhat similar case, when I want a python program to build up some commands and then run them, with the output going to the user who fired off the script. The code I use is:
import subprocess
def run(cmd):
call = ["/bin/bash", "-c", cmd]
ret = subprocess.call(call, stdout=None, stderr=None)
if ret > 0:
print "Warning - result was %d" % ret
run("javac foo.java")
run("javac bar.java")
In my case, I want all commands to run error or not, which is why I don't have an exception raised on error. Also, I want any messages printed straight to the terminal, so I have stdout and stderr be None which causes them to not go to my python program. If your needs are slightly different for errors and messages, take a look at the http://docs.python.org/library/subprocess.html documentation for how to tweak what happens.
(I ask bash to run my command for me, so that I get my usual path, quoting etc)
回答2:
os.system should return 0 when the command executes correctly. 0 is the standard return code for success.
Does it print output when run from the command line?
回答3:
Why would you want to do this in Python? For tasks like this, especially Java, you are better off using Apache Ant. Write commands in xml and then ant runs for you.
来源:https://stackoverflow.com/questions/5532481/execute-jar-from-python