gansub gansub - 4 months ago 16x
Python Question

Python script : Running a script with multiple arguments using subprocess

My question is related to this earlier question - Python subprocess usage

I am trying to run this command using python

nccopy -k 4 "[408:603][2][20:34][26:40]"

When I run the above command I should be able to see a file called on my disk or a network error stating unable to access that URL or remote URL not found.

Currently the ESRL NOAA server is down - so when I run the above command I get

syntax error, unexpected $end, expecting SCAN_ATTR or SCAN_DATASET or SCAN_ERROR
context: ^
NetCDF: Access failure
Location: file nccopy.c; line 1348

I should get the same error when I run the python script

This is the code I have and I am unable to figure out exactly how to proceed further -

I tried splitting up "-k 4" into two arguments and removing the quotes and I still get this error nccopy : invalid format : 4

Results of print(sys.argv)

['', '-k', '4', '[480:603][20:34][26:40]', '']

import numpy as np

import subprocess

import sys

url = '"[408:603][2][20:34][26:40]"'

outputFile = ''

arg1 = "-k 4"

arg3 = url

arg4 = outputFile

print (input)



There's two dilemmas here.
One being that subprocess processes your arguments and tries to use 4 as a separate argument.

The other being that system calls still goes under normal shell rules, meaning that parameters and commands will be parsed for metacharacters aka special characters. In this case you're wrapping [ and ].

There for you need to separate each parameters and it's value into separate objects in the parameter-list, for instance -k 4 should be ['-k', '4'] and you need to wrap parameters/values in '...' instead of "...".

Try this, shlex.split() does the grunt work for you, and i swapped the encapsulation characters around the URL:

import numpy as np
import subprocess
import sys
import shlex

url = "'[408:603][2][20:34][26:40]'"

outputFile = ''
command_list = shlex.split('nccopy -k 4 ' + url + ' ' + outpufFile)