Announcement

Collapse
No announcement yet.

Question for Python Coders

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Question for Python Coders

    I am new to Python and know that there is an easier way but I can't seem to figure out what it is. I want to strip some characters from a string and this is the way I did it:

    Code:
    filenametmp = 'pageadmin' + str(datetime.datetime.utcnow())
    filenametmp2 = filenametmp.replace('-','')
    filenametmp3 = filenametmp2.replace(':','')
    filenametmp4 = filenametmp3.replace('.','')
    filename = filenametmp4.replace(' ','')
    filename = filename + '.txt'
    I tried:
    Code:
    filenametmp = 'pageadmin' + str(datetime.datetime.utcnow())
    filename = filenametmp.strip(':-.')
    But I don't think that is the right BIF because it only affects leading and trailing; at least based on the documentation. What am I missing? If there are other suggestions related to getting the timestamp without all the dashes, semi-colons, and periods, I am open to those as well.

    [volun]

  • #2
    Re: Question for Python Coders

    Ya, strip won't do it. You could use a list comprehension like this:
    Code:
    timestmp = str(datetime.datetime.utcnow()
    badchars = '-:. '
    filename = 'pageadmin'.join([ch for ch in timestmp if not in badchars])
    Peace through fear... since 1947!

    Comment


    • #3
      Re: Question for Python Coders

      Does Python have any regex processing? In Perl, one would do something like "s/[:-.]//g". (I may have it not quite right. I know what goes in the slashes, but I always have to look up the syntax for how to embed a regex in a particular case, like a search-and-replace.)
      Dude, seriously, WHAT handkerchief?

      snooggums' density principal: "The more dense a population, the more dense a population."

      Iliana: "You're a great friend but if we're ever chased by zombies I'm tripping you."

      Comment


      • #4
        Re: Question for Python Coders

        I'd use the string module and a loop.

        Code:
        import string
        filename = 'pageadmin' + str(datetime.datetime.utcnow())
        for eachchar in string.punctuation + string.whitespace:
           filenametmp.replace(eachchar, '')
        filename = filename + '.txt'
        [volun2]
        NS Game Officer. TF2 Admin. BF2 Admin / Scripter. PM with issues.
        Tempus: Pokerface is nailing it right on the head. Everyone who is arguing against him is simply arguing against reality.
        <anmuzi> it is not permitted to have privacy or anonymity
        <LazyEye> yeah when I play on TG the server digs though my trash

        Arm yourself with knowledge: TG NS TF2 BF2

        Comment


        • #5
          Re: Question for Python Coders

          Thanks for the suggestions. I knew there had to be something else that would work.

          Another couple questions that have been plaguing me due to lack of knowledge.

          (1) I am trying to delete the file from the local file system but it keeps failing. My code looks like this:
          Code:
          try:
                   os.unlink(filename)
          except:
                   host.rcon_invoke('echo "Could not delete %s"' % (filename))
          The messsage I get back from the echo has the correct filename in it but it won't delete it.

          (2) Since I am running this as a module in BF2, is there any way for me to get better debugging info like writing to a file. For example, the delete function doesn't work and I assume there is an error message that does along with it but I can't see it. I've looked at the documentation regarding handlling exceptions but it may as well be written in Greek.

          [volun]

          Comment


          • #6
            Re: Question for Python Coders

            Originally posted by Killer_McDermott View Post
            Thanks for the suggestions. I knew there had to be something else that would work.

            Another couple questions that have been plaguing me due to lack of knowledge.

            (1) I am trying to delete the file from the local file system but it keeps failing. My code looks like this:
            Code:
            try:
                     os.unlink(filename)
            except:
                     host.rcon_invoke('echo "Could not delete %s"' % (filename))
            The messsage I get back from the echo has the correct filename in it but it won't delete it.

            (2) Since I am running this as a module in BF2, is there any way for me to get better debugging info like writing to a file. For example, the delete function doesn't work and I assume there is an error message that does along with it but I can't see it. I've looked at the documentation regarding handlling exceptions but it may as well be written in Greek.
            BF2's python functionality is crippled, especially in the OS department. They wanted it to be useful to game scripting, but not malicious kill-your-computer stuff.

            So far as seeing output, I used this GUI log when testing scripts. It effectively shows a python console during the server process. Unzip it into X:\Program Files\EA GAMES\BF2ServerFolder\python\bf2\ and doubleclick the .pyw file BEFORE launching the server.
            Attached Files
            [volun2]
            NS Game Officer. TF2 Admin. BF2 Admin / Scripter. PM with issues.
            Tempus: Pokerface is nailing it right on the head. Everyone who is arguing against him is simply arguing against reality.
            <anmuzi> it is not permitted to have privacy or anonymity
            <LazyEye> yeah when I play on TG the server digs though my trash

            Arm yourself with knowledge: TG NS TF2 BF2

            Comment


            • #7
              Re: Question for Python Coders

              Originally posted by Pokerface View Post
              BF2's python functionality is crippled, especially in the OS department. They wanted it to be useful to game scripting, but not malicious kill-your-computer stuff.

              So far as seeing output, I used this GUI log when testing scripts. It effectively shows a python console during the server process. Unzip it into X:\Program Files\EA GAMES\BF2ServerFolder\python\bf2\ and doubleclick the .pyw file BEFORE launching the server.
              Thanks. I was just trying to figure out how to get rid of the files from the local machine so it didn't get clogged up. They are probably only 1K a piece but it is still clutter. I will try GUI Log.

              [volun]

              Comment


              • #8
                Re: Question for Python Coders

                Ah, Python has regexs. Here's a section on search-and-replace:

                http://www.amk.ca/python/howto/regex...00000000000000

                Looks like you can do something like this:

                Code:
                p = re.compile('[-:.]')
                p.sub('', filename)
                Note that my earlier example had a bug. "[:-.]" is the range of characters from ":" to ".". One has to put the dash up front to make it not indicate a range.
                Dude, seriously, WHAT handkerchief?

                snooggums' density principal: "The more dense a population, the more dense a population."

                Iliana: "You're a great friend but if we're ever chased by zombies I'm tripping you."

                Comment


                • #9
                  Re: Question for Python Coders

                  The most likely reason for unlink to fail on Windows is that some process has the file locked.

                  In Linux, this isn't as much a problem, because unlink doesn't actually delete the file. It just removes the directory link. The file continues to exist, nameless, until the last process closes it. (There's a reference count in memory that counts how many filesystem hard links point to the file and how many processes have the file open. When this count goes to zero, the filesystem storage (ie. disk blocks) is deallocated.)
                  Dude, seriously, WHAT handkerchief?

                  snooggums' density principal: "The more dense a population, the more dense a population."

                  Iliana: "You're a great friend but if we're ever chased by zombies I'm tripping you."

                  Comment


                  • #10
                    Re: Question for Python Coders

                    Originally posted by ScratchMonkey View Post
                    Ah, Python has regexs. Here's a section on search-and-replace:

                    http://www.amk.ca/python/howto/regex...00000000000000

                    Looks like you can do something like this:

                    Code:
                    p = re.compile('[-:.]')
                    p.sub('', filename)
                    Note that my earlier example had a bug. "[:-.]" is the range of characters from ":" to ".". One has to put the dash up front to make it not indicate a range.
                    I will give this a shot also. For some reason the other suggestions didn't work. I copied the code exactly but it didn't produce the desired results so I reverted back to my original code just to get things working. I can always optimize later.

                    [volun]

                    Comment


                    • #11
                      Re: Question for Python Coders

                      Originally posted by ScratchMonkey View Post
                      The most likely reason for unlink to fail on Windows is that some process has the file locked.

                      In Linux, this isn't as much a problem, because unlink doesn't actually delete the file. It just removes the directory link. The file continues to exist, nameless, until the last process closes it. (There's a reference count in memory that counts how many filesystem hard links point to the file and how many processes have the file open. When this count goes to zero, the filesystem storage (ie. disk blocks) is deallocated.)
                      Thanks for the info. If I type the code into the Python console, it will delete just fine but I have to put a complete path, e.g. /Program Files/EA GAMES...., in order for it to work so I thought I would try to use a variable and then concatenate the path and filename together and then try the unlink. It was a nice idea but it still doesn't work. There is yet another thing for me to try and figure out. Right now I am going to concentrate on getting the script to do what I want for the most part and then work on some of the clean up. If I keep getting stuck on these little things, I'll never get it done but I guess I could look at it as a learning experience. ;)

                      [volun]

                      Comment


                      • #12
                        Re: Question for Python Coders

                        Originally posted by Pokerface View Post
                        BF2's python functionality is crippled, especially in the OS department. They wanted it to be useful to game scripting, but not malicious kill-your-computer stuff.

                        So far as seeing output, I used this GUI log when testing scripts. It effectively shows a python console during the server process. Unzip it into X:\Program Files\EA GAMES\BF2ServerFolder\python\bf2\ and doubleclick the .pyw file BEFORE launching the server.
                        Anything else I have to do special to get this to work? I extracted it to the location you said and started it before I started my server but nothing comes up in the window. It isn't a ModManager thing is it?

                        [volun]

                        Comment


                        • #13
                          Re: Question for Python Coders

                          Originally posted by Killer_McDermott View Post
                          I will give this a shot also. For some reason the other suggestions didn't work. I copied the code exactly but it didn't produce the desired results so I reverted back to my original code just to get things working. I can always optimize later.
                          Hrm... I didn't test the list comprehension stuff, but it should work unless I made a silly error....... lol

                          Ok, sorry. I made a silly error which would have been avoided if I spelled it out.

                          Code:
                          timestmp = str(datetime.datetime.utcnow()
                          badchars = '-:. '
                          filename = 'pageadmin'.join([ch for ch in timestmp if ch not in badchars])
                          (I forgot the 3rd 'ch')

                          The part in [] makes a list of characters which consists of every character in timestmp which is not in badchars. Then the join takes that list and joins it to the string to get the final filename.

                          I searched and found a page full of examples including one very similar to this.
                          Peace through fear... since 1947!

                          Comment


                          • #14
                            Re: Question for Python Coders

                            Originally posted by Killer_McDermott View Post
                            Anything else I have to do special to get this to work? I extracted it to the location you said and started it before I started my server but nothing comes up in the window. It isn't a ModManager thing is it?
                            MMMMMMMmmm........... Something occurs to me; not everyone has Python installed. That's a requisite for the gui log to work.
                            [volun2]
                            NS Game Officer. TF2 Admin. BF2 Admin / Scripter. PM with issues.
                            Tempus: Pokerface is nailing it right on the head. Everyone who is arguing against him is simply arguing against reality.
                            <anmuzi> it is not permitted to have privacy or anonymity
                            <LazyEye> yeah when I play on TG the server digs though my trash

                            Arm yourself with knowledge: TG NS TF2 BF2

                            Comment


                            • #15
                              Re: Question for Python Coders

                              Originally posted by Pokerface View Post
                              MMMMMMMmmm........... Something occurs to me; not everyone has Python installed. That's a requisite for the gui log to work.
                              I have Python installed. I am running 2.5. There isn't a flag I have to set or anything is there?

                              [volun]

                              Comment

                              Connect

                              Collapse

                              TeamSpeak 3 Server

                              Collapse

                              Advertisement

                              Collapse

                              Twitter Feed

                              Collapse

                              Working...
                              X