open( "file","mode") difference between script and commandline?

Donn Cave donn at oz.net
Sun Nov 7 13:53:53 EST 1999


Quoth Michael Praschl <praschl at bigfoot.com>:
| im using python 1.5.2 for BeOS

Life can be sweet!

| and im having a problem with file opening. when i use 
|
| >>> f = open( "filename","w" ) 
|
| in the command line interface, this works perfectly ok. but when i use
| the same function from a script, i get the following error: 
|
| Traceback (innermost last): 
|   File "Signmail.py", line 19, in ? 
|     f = open( "/tmp/workfile", "w" ) 
| TypeError: illegal argument type for built-in operation 
|
| can anybody tell me why this is? and what i can do about it? 

Yes, but it's just lucky that you handed us the clue in the next
question.  You apparently start your program with
   from os import *

Now this imports an "open", the POSIX 1003.1 open() function whose
arguments are (string, int [, int])  You may want to use this function
some day, but what you should do the minute you read this message is
remove all "from module import *" from your programs and start fixing
up the module references.  The problem you just had is a terrific
example of the pernicious problems posed by this practice.

| the second problem i found while i was trying to get around this. i have
| a multiline string (linefeeds) in the variable reply, and want to do the
| following: 
|
| system( "echo >/tmp/pgpBeMail `reply`" )  #reply is within this "\"
| apostrphys (in case the newsreaders cant show them correctly) 
|
| in this case the file is empty after the call. i tried also turning to
| this "/" apostrophys and to normal ones, but then the file contains
| "reply" as expected, but not the contents of "reply" 

[Of course this will be os.system() once you've fixed that.]

Python string quoting isn't the art it is with some other more
shell-like interpreted languages.  You quote to get a string, and
then what's inside the quotes is pretty much the literal contents
of the string, there's no provision for evaluating variables in
there.  So the shell got your ` intact, and tried to execute "reply",
since that's its cue for a command expansion.

Now the string you need here should to include its own quotes around
the data you want to echo, to keep the shell from getting tangled up
interpreting that data - so you want the system() call to look like 
system( "echo > /tmp/pgpBeMail 'some reply data'" )  And note that
echo will add a newline to the end anyway.

So a couple of ways to generate this might be
    os.system("echo > /tmp/pgpBeMail '%s'" % reply)

    os.system("echo > /tmp/pgpBeMail '" + reply + "'")

	Donn Cave, donn at oz.net




More information about the Python-list mailing list