strange behaviour sys.argv

Charles Sanders C.delete_this.Sanders at BoM.GOv.AU
Tue Apr 17 05:00:16 CEST 2007

Michael Hoffman wrote:
> schnupfy wrote:
>> I am not used to python and I am wondering about this thing:
> This is not a Python question. It is a question about how to use bash.

Michael is correct, it is a bash thing, nothing to do with python.
bash (and other *nix like shells) generally break arguments on
white space. Quoting (both single and double) overrides this with
(slightly) different rules for different shells.

 > /root/mk/ critical "
 > SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-
 > MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2-
 > SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical"
 > MIB::snmpTrapCommunity.0 "public""

	Assuming this has been folded and actually is one long
line (which the output confirms), you have passed the python
script seven arguments

	''  (blank seperated)
	'critical'       (also blank seperated)
a string extending from just after the first double quote to
just before the second, ie starting with '' and
ending with '789.0.2', with the immediately following (no
white space) unquoted text 'fCannotTakeover' appended
	'=='             (blank seperated)
a string starting with critical, with the quoted string from
'SNMP-COMMUNITY' to 'Community.0 ' (including the blank), the
unquoted string 'public', and the null quoted string "" all

 > TRAP=' SNMPv2-MIB::sysUpTime.0
 > 14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.
 > 789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1
 > priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0
 > SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"'
 > HOST=$(echo "$TRAP" | awk '{print $1}')
 > SEVERITY='critical'
 > /root/mk/ $HOST $SEVERITY \"$TRAP\"

	Here, the variables are expanded, and then split into
arguments on white space unless quoted. The backslashes protect
the double quotes so they are treated as normal characters, so
the $TRAP variable is also split into arguments on white space.
Quotes resulting from the substitution of $TRAP are also protected
(ie are treated as ordinary characters).

The result is

	'"   (From $HOST)
	'critical'        (From $SEVERITY)
	'"'  (Leading '"' from \", rest from
			   $TRAP, blank seperated)
	''   (from $TRAP, blank seperated)
and so on for the rest of the $TARP string, splitting it at
white space. The last part of $TRAP, '"public"', has a double
quote appended from the \".

Python is giving exactly what the shell has given it in both cases.


More information about the Python-list mailing list