1

This is a simple command that works from command line:

> python -c "print('asdasd')"
asdasd

But it fails to output anything when executed from the script:

import os
import sys
import subprocess

cmd = [sys.executable] + ['-c', '"print(\'asdasd\')"']
print cmd
kwargs = {
  'stdout': subprocess.PIPE,
  'stderr': subprocess.PIPE,
  'stdin': subprocess.PIPE,
}

print subprocess.Popen(cmd).communicate()
print subprocess.Popen(cmd, **kwargs).communicate()

The output:

['C:\\Python27\\python.exe', '-c', '"print(\'asdasd\')"']
(None, None)
('', '')

Why it doesn't produce anything? I am out of ideas. Looks like a bug in Python 2.7.11 to me.

2 Answers 2

1

First, you don't need those extra double-quotes for '"print(\'asdasd\')"' in your command line arguments. As it is, your code will just execute a python code that do the following: "print(\'asdasd\')". In other word, it will produce the string: print(\'asdasd\')

Obviously, creating a string won't print anything. Here is a patched version of your code:

import os
import sys
import subprocess

cmd = [sys.executable] + ['-c', 'print(\'asdasd\')']
print cmd
kwargs = {
    'stdout': subprocess.PIPE,
    'stderr': subprocess.PIPE,
    'stdin': subprocess.PIPE,
}

print subprocess.Popen(cmd).communicate()
print subprocess.Popen(cmd, **kwargs).communicate()

You may want to use the shlex module to parse your command line argument.

For example, using the shlex module and the triple quotes with a string format (do not forget quotes for the python path, otherwise characters such as backslash will be interpreted):

import sys
import shlex
import subprocess

cmd_str = '''"{}" -c "print('asdasd')"'''.format(sys.executable)
print(cmd_str)
cmd = shlex.split(cmd_str)
print(cmd)
kwargs = {
    'stdout': subprocess.PIPE,
    'stderr': subprocess.PIPE,
    'stdin': subprocess.PIPE,
}
print(subprocess.Popen(cmd).communicate())
print(subprocess.Popen(cmd, **kwargs).communicate())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I knew there is something obvious, but I thought it is somewhere in subprocess. I quoted the string, because it was quoted in raw command line, but when arguments are expressed in a list, Python quotes them itself.
0

Try this:

subprocess.Popen(['{} -c "print(\'ECHO\')"'.format(sys.executable)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

1 Comment

@anatolytechtonik Edited, give it another try.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.