Reputation: 51824
I am trying to insert the file content of an multi-line SQL file within a Python script:
sql_file = open(sql_file_path, 'r')
file_content = sql_file.read()
file_content = file_content.replace("placeholder", "realvalue")
import_cmd = 'ogr2ogr -f "PostgreSQL" \
-lco GEOMETRY_NAME=the_geom \
PG:"host=localhost user={db_user_name} port=5432 \
dbname={db_name} password={db_password}" \
{source_file} -nln "{db_table_name}" \
-sql "$(cat {file_content})"'
os.system(import_cmd.format(
db_user_name=db_user_name,
db_name=db_name,
db_password=db_password,
source_file=source_file,
db_table_name=db_table_name,
file_content=file_content
))
The file sql_file_path
contains multiple lines. The content is modified via replace
. Then th new file_content
has to be appended to the -sql
parameter of the ogr2ogr
command line tool. However, the script throws this error:
Syntax error: "(" unexpected (expecting ")")
Upvotes: 0
Views: 124
Reputation: 1122012
Don't use os.system
. Use subprocess.call()
and pass in your arguments as a list:
import subprocess
conn_info = (
'PG:host=localhost user={db_user_name} port=5432 '
'dbname={db_name} password={db_password}'.format(
db_user_name=db_user_name,
db_name=db_name,
db_password=db_password))
subprocess.call([
'ogr2ogr', '-f', 'PostgreSQL', '-lco', 'GEOMETRY_NAME=the_geom',
conn_info, source_file, '-nln', db_table_name, '-sql', file_content])
This won't go through a shell but invokes the program directly, and each argument passed in directly as is. No further quoting required.
Upvotes: 1