1

I am attempting to create a Python script that in turn runs the shell script "js2coffee" to convert some javascript into coffeescript.

From the command line I can run this, and get coffeescript back again...

echo "var myNumber = 100;" | js2coffee

What I need to do is use this same pattern from Python.

In Python, I've come to something like this:

command = "echo '" + myJavscript + "' | js2coffee"
result = os.popen(command).read()

This works sometimes, but there are issues related to special characters (mostly quotes, I think) not being properly escaped in the myJavascript. There has got to be a standard way of doing this. Any ideas? Thanks!

1

2 Answers 2

5

Use the input stream of a process to feed it the data, that way you can avoid the shell and you don't need to escape your javascript. Additionally, you're not vulnerable to shell injection attacks;

pr = subprocess.Popen(['js2coffee'], 
                      stdin=subprocess.PIPE,  
                      stdout=subprocess.PIPE)
result, stderrdata = pr.communicate('var myNumber = 100;')
0
1

subprocess module is the way to go: http://docs.python.org/library/subprocess.html#frequently-used-arguments

be kindly noted the following:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.