1

I try the following command:

subprocess.call(['sudo', 'su - postgres'], shell=True)

or

subprocess.call(['sudo', 'su', '-', 'postgres'], shell=True)

in Python2.7 (either by ipython manually writing the line, or python myfile.py being the line as part of the code), and get the sudo usage information:

usage: sudo [-D level] -h | -K | -k | -V
usage: sudo -v [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-u user
        name|#uid]
usage: sudo -l[l] [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-U user
        name] [-u user name|#uid] [-g groupname|#gid] [command]
usage: sudo [-AbEHknPS] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u
        user name|#uid] [-g groupname|#gid] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u
        user name|#uid] file ...

I can run the command in the shell with no problems at all. Both times it is the same shell.

Q: What am I doing wrong?

2
  • Isn't placing a list of arguments done consecutively? Commented Jun 4, 2015 at 17:07
  • Wait. There are many other better ways to connect to postgres. Why are you using this? BTW to solve your problem you can do subprocess.call(['sudo su - postgres'], shell=True) Commented Jun 4, 2015 at 17:09

1 Answer 1

4

From the subprocess docs:

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). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

Therefore, your list is really a sequence. For a single command, just place the string, together, as there is no need to have it split:

subprocess.call(['sudo su - postgres'], shell=True)
Sign up to request clarification or add additional context in comments.

Comments

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.