When I tried to run psql indirectly using subprocess.check_output (), I ran into the error "
psql: Invalid option --'''
". I couldn't figure out what was wrong with this message alone, so I tried various things to find out the cause.
As a result, I found that there was a problem with how to create the arguments.
I ran a command in Python that remotely lists the users of the PostgreSQL server.
Problem code psql01.py
#!/usr/bin/env python
import subprocess
cmd = [
'psql',
'-U ' + 'postgres',
'-d ' + 'postgres',
'-t ',
'-c ' + 'select * from pg_user;'
]
try:
result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
result = e.output
print result
Command execution (error)
[user001@localhost ~]$ python psql01.py
['psql', '-U postgres', '-d postgres', '-t ', '-c select * from pg_user;']
psql:Invalid option-- ' '
Detail is"psql --help"Please see.
The method of creating the second argument of check_output () set in the cmd variable of the above sample code has been modified.
check_output syntax
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
For example, when parsing a command line (with getopt etc.) in bash or C language, whitespace characters are interpreted as delimiters, but check_output () seems to have list elements as argument elements. To put it badly, check_output () doesn't seem to treat whitespace as a delimiter.
cmd = [
'psql',
'-U' , 'postgres',
'-d' , 'postgres',
'-t',
'-c' , 'select * from pg_user;'
]
cmd = [
'psql',
'-U' + 'postgres',
'-d' + 'postgres',
'-t',
'-c' + 'select * from pg_user;'
]
psql: Invalid option--'''
" seems to point to a syntax error of'-t △'(whitespace after t).Recommended Posts