J. Doe J. Doe - 1 month ago 9
Python Question

Getting an AWK command to work in Python script

I have this command in my Python script -

client.connect(host, username=username, pkey=mykey)
stdin, stdout, stderr = client.exec_command('sudo grep -i "key_prefix" /path/to/my/file.txt | awk -F "'" '{ print $4}'')


However, I get the following error -
SyntaxError: EOL while scanning string literal


How could I get the python script to cut up the string correctly?

This is the string I am performing the awk on -

$conf['key_prefix'] = 'my_string';
. The value that I want is the my_string value. Inside of the bash console, it works correctly, but the python script throws an error.

If I add then all into a list, the value at index 0 of the list is this -

uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$conf['key_prefix'] = 'my_string';
$conf['key_prefix'] = 'my_string';


Any ideas to get the awk command to work? Seems to be the easiest solution to the issues.

Thanks.

Answer

fairly certain you want to use some triple quotes here.

stdin, stdout, stderr = client.exec_command('sudo grep -i "key_prefix" /path/to/my/file.txt | awk -F "'" '{ print $4}'')

should become

stdin, stdout, stderr = client.exec_command("""sudo grep -i "key_prefix" /path/to/my/file.txt | awk -F "'" '{ print $4}'""")

The problem (based off what I can see) is that your first ' is matched right after the -F" and then you have a " after it which starts a new string. Could be wrong but try triple quotes and see if that helps.