Community
    • Login

    Issues Running Python Scripts in Batch File

    Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
    10 Posts 4 Posters 739 Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • ImJohnFolksI
      ImJohnFolks
      last edited by

      Hello Community,

      I am currently facing some challenges running Python scripts through a batch file, and I would greatly appreciate your assistance in resolving the issue. Here are the details:

      Problem Description:
      I have a batch file that I believe is supposed to run multiple Python scripts on files that I drag and drop on to the batch file. However, I am encountering difficulties, and I suspect there might be an issue with the way it’s set up.

      Batch File Content:

      @echo off
      
      rem List of Python scripts to run
      set "scripts=BrakesDelayTimes.py CriticalDamageThresholdTimes.py DamageCapacityTimes.py DamagedConsumptionModifierTimes.py DamagedMaxTorqueMultiplierTimes.py DamagedMinTorqueMultiplierTimes.py EngineResponsivenessTimes.py FuelConsumptionTimes.py TorqueTimes.py"
      
      rem Path to your Python executable
      set "python_executable=C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.496.0_x64__qbz5n2kfra8p0\python3.12.exe"
      
      rem Loop through the scripts and run them
      for %%i in (%scripts%) do (
          echo Running script: %%i
          "%python_executable%" "%%i"
      )
      

      Additional Information:

      • Example of one of the python scripts
      # encoding=utf-8
      from Npp import editor
      
      def multiply_by_2(m):
          return 'BrakesDelay="' + str(float(m.group(1))*1.08) + '"'
       
      
      editor.rereplace(r'BrakesDelay="(\d*\.?\d*.\d+)"', multiply_by_2)
      
      • Operating System: [Windows 11]
      • Python Version: [Python 3.12]

      Request for Assistance:
      If anyone has experience with running Python scripts through a batch file, could you please review my batch file and paste the new batch file. Thank you in advance for your time and assistance!

      Best regards,
      ImJohnFolks

      EkopalypseE 1 Reply Last reply Reply Quote 0
      • EkopalypseE
        Ekopalypse @ImJohnFolks
        last edited by

        @ImJohnFolks said in Issues Running Python Scripts in Batch File:

        from Npp import editor

        They import objects that are exposed by the PythonScript plugin and are only available through it. This means that such scripts only run in an instance of Npp in which this plugin is loaded, and NEVER outside of Npp, i.e. within a cmd shell.

        ImJohnFolksI 1 Reply Last reply Reply Quote 3
        • ImJohnFolksI
          ImJohnFolks @Ekopalypse
          last edited by ImJohnFolks

          @Ekopalypse said in Issues Running Python Scripts in Batch File:

          They import objects that are exposed by the PythonScript plugin and are only available through it. This means that such scripts only run in an instance of Npp in which this plugin is loaded, and NEVER outside of Npp, i.e. within a cmd shell

          Thank you for your swift response regarding the limitations of trying to use batch files to run multiple scripts at once.

          Given this information, I’m curious to know if there’s a recommended way to achieve a similar batch-like execution of multiple Python scripts directly within Notepad++. Is there an alternative approach? Or is it not feasible to achieve this within Notepad++?

          Thank you for your assistance!

          Here is a quick overview
          Untitledvideo-MadewithClipchamp-ezgif.com-video-to-gif-converter.gif

          Alan KilbornA 1 Reply Last reply Reply Quote 0
          • Alan KilbornA
            Alan Kilborn @ImJohnFolks
            last edited by Alan Kilborn

            @ImJohnFolks

            IMO the best idea here is to forget Notepad++ being involved in the solution, and using only a Python solution. You obviously already have a standalone Python on your system, know something about programming in Python, etc.

            So you just have to figure out how to do the operations you’d do using editor.xxx() and/or notepad.xxx() PythonScript functions a different way. Doing it in standalone Python is only slightly harder than with a PythonScript assist. From your example script, instead of editor.rereplace(), I’d suggest re.sub().

            And that’s as far as I’ll go because as soon as Notepad++ gets chopped out of the discussion, this all becomes off-topic for this forum.

            ImJohnFolksI 1 Reply Last reply Reply Quote 4
            • ImJohnFolksI
              ImJohnFolks @Alan Kilborn
              last edited by

              Okay, for the past few hours, I’ve been unsuccessful in trying to get this working in the default Python environment.

              So, I attempted to find a solution within Notepad++ and came across this post [Hmm it appears I can’t post links]. However, the code in that post isn’t working as intended either.

              Here’s the code I’m using from that post:

              from Npp import *
              
              def forEachFile(func):
                  for file in notepad.getFiles():
                      notepad.activateBufferID(file[1])
                      func()
              
              def printFilename():
                  print(notepad.getCurrentFilename())
              
              # store the current buffer id
              currentBufferID = notepad.getCurrentBufferID()
              # run our printFilename function on each open file
              forEachFile(printFilename)
              # restore the current buffer from the stored buffer id.
              notepad.activateBufferID(currentBufferID)
              

              When I place this in my Script py, I get the following output in the Python console:

              C:\Program Files\Notepad++\plugins\PythonScript\scripts\SnowRunnerPythonScripts\Engines\EnginesBrakesDelayTimes.py
              C:\Users\johnr\Desktop\[media]\classes\engines\e_us_scout_old.xml
              C:\Users\johnr\Desktop\[media]\classes\engines\e_ru_scout_modern.xml
              

              My Script py:

              # encoding=utf-8
              from Npp import editor
              
              def forEachFile(func):
                  for file in notepad.getFiles():
                      notepad.activateBufferID(file[1])
                      func()
              
              def printFilename():
                  print(notepad.getCurrentFilename())
              
              # store the current buffer id
              currentBufferID = notepad.getCurrentBufferID()
              # run our printFilename function on each open file
              forEachFile(printFilename)
              # restore the current buffer from the stored buffer id.
              notepad.activateBufferID(currentBufferID)
              
              def multiply_by_2(m):
                  return 'BrakesDelay="' + str(float(m.group(1))*1.08) + '"'
              
              editor.rereplace(r'BrakesDelay="(\d*\.?\d*.\d+)"', multiply_by_2)
              

              However, the output files aren’t changed at all. I assume I’m doing something wrong in the ‘func()’ part where I’m supposed to insert something??? Could you please help me figure this out? Thank you.

              PS Im new so be kind I have no experince in python or notepad etc

              PeterJonesP 1 Reply Last reply Reply Quote 0
              • PeterJonesP
                PeterJones @ImJohnFolks
                last edited by

                @ImJohnFolks ,

                The example you were copying from was just using printFilename() as an example of something you could do on all files: it was a dummy/placeholder, not the end goal.

                What you really need to do is to define your own function, which calls the editor.rereplace . You would then call that function instead of calling printFilename in the forEachFile(...) call.

                ImJohnFolksI 1 Reply Last reply Reply Quote 0
                • ImJohnFolksI
                  ImJohnFolks @PeterJones
                  last edited by ImJohnFolks

                  @PeterJones said in Issues Running Python Scripts in Batch File:

                  @ImJohnFolks ,

                  The example you were copying from was just using printFilename() as an example of something you could do on all files: it was a dummy/placeholder, not the end goal.

                  What you really need to do is to define your own function, which calls the editor.rereplace . You would then call that function instead of calling printFilename in the forEachFile(...) call.

                  @PeterJones,

                  I appreciate your assistance thus far.

                  I am really new to Python, scripting and Notepad ++ and I am having difficulty understanding the concept you mentioned in your previous response. Specifically, you suggested defining my own function that calls ‘editor.rereplace’ and then using that function in place of the ‘printFilename’ called within the ‘forEachFile(…)’.

                  Below is my attempt at implementing what I believe you were suggesting:

                  # encoding=utf-8
                  from Npp import editor
                  
                  def forEachFile(func):
                      for file in notepad.getFiles():
                          notepad.activateBufferID(file[1])
                          func()
                  
                  def multiply_by_2(m):
                      return 'BrakesDelay="' + str(float(m.group(1))*1.08) + '"'
                  
                  def printFilename():
                      print(notepad.getCurrentFilename())
                  
                  # Store the current buffer id
                  currentBufferID = notepad.getCurrentBufferID()
                  
                  # Run our printFilename function on each open file
                  forEachFile(editor.rereplace(r'BrakesDelay="(\d*\.?\d*.\d+)"', multiply_by_2))
                  
                  # Restore the current buffer from the stored buffer id
                  notepad.activateBufferID(currentBufferID)
                  

                  It seems like I am missing something, could you kindly provide further clarification or perhaps an illustrative example to help me better understand the process?

                  Thank you in advance for your time and assistance.

                  PeterJonesP 1 Reply Last reply Reply Quote 0
                  • PeterJonesP
                    PeterJones @ImJohnFolks
                    last edited by

                    @ImJohnFolks said in Issues Running Python Scripts in Batch File:

                    I am really new to Python, scripting and Notepad ++ and I am having difficulty understanding the concept you mentioned in your previous response. Specifically, you suggested defining my own function that calls ‘editor.rereplace’ and then using that function in place of the ‘printFilename’ called within the ‘forEachFile(…)’.

                    This is not a Python help forum. Defining a function is very much generic Python programming.

                    But in brief, it’s the def XXXXX(arg):
                    So you would need to do something like the following (untested) to define your function:

                    def doMyReplacement():
                        editor.rereplace(r'BrakesDelay="(\d*\.?\d*.\d+)"', multiply_by_2)
                    

                    Then the forEachFile line should be:

                    forEachFile(doMyReplacement)
                    

                    If you are going to continue to develop in PythonScript, you will need to learn the fundamentals of Python – and we cannot teach those to you. You will have to find some other tutorial on the web to learn the essentials of Python.

                    ImJohnFolksI 1 Reply Last reply Reply Quote 2
                    • ImJohnFolksI
                      ImJohnFolks @PeterJones
                      last edited by

                      @PeterJones said in Issues Running Python Scripts in Batch File:

                      @ImJohnFolks said in Issues Running Python Scripts in Batch File:

                      I am really new to Python, scripting and Notepad ++ and I am having difficulty understanding the concept you mentioned in your previous response. Specifically, you suggested defining my own function that calls ‘editor.rereplace’ and then using that function in place of the ‘printFilename’ called within the ‘forEachFile(…)’.

                      This is not a Python help forum. Defining a function is very much generic Python programming.

                      But in brief, it’s the def XXXXX(arg):
                      So you would need to do something like the following (untested) to define your function:

                      def doMyReplacement():
                      editor.rereplace(r’BrakesDelay=“(\d*.?\d*.\d+)”', multiply_by_2)
                      Then the forEachFile line should be:

                      forEachFile(doMyReplacement)
                      If you are going to continue to develop in PythonScript, you will need to learn the fundamentals of Python – and we cannot teach those to you. You will have to find some other tutorial on the web to learn the essentials of Python.

                      @PeterJones

                      I appreciate your guidance and clarification. Thank you for sharing the snippet for defining a function in Python, and I kind of understand your point about the forum’s focus and apologies for any confusion caused by my assumption about the nature of this forum. I did notice the “Help wanted” tag and thought it implied assistance could be sought here. Regardless, I appreciate your feedback.

                      With your help, (its took me around 4 hours of just F’ing around) I’ve managed to make some progress on my PythonScript within Notepad++. For the benefit of others facing a similar issue, here’s the code that worked for me:

                      # encoding=utf-8
                      from Npp import editor, notepad
                      
                      def multiply_by_2(m):
                          return 'BrakesDelay="' + str(float(m.group(1))*1.08) + '"'
                      
                      # Define the replacement function
                      def doMyReplacement():
                          editor.rereplace(r'BrakesDelay="(\d*\.?\d*.\d+)"', multiply_by_2)
                      
                      def forEachFile(doMyReplacement):
                          for file in notepad.getFiles():
                              notepad.activateBufferID(file[1])
                              doMyReplacement()
                      
                      def printFilename():
                          print(notepad.getCurrentFilename())
                      
                      # Store the current buffer id
                      currentBufferID = notepad.getCurrentBufferID()
                      
                      # Run our printFilename function on each open file
                      forEachFile(doMyReplacement)
                      
                      # Restore the current buffer from the stored buffer id
                      notepad.activateBufferID(currentBufferID)
                      

                      Thanks again for your help and clear guidance.

                      PeterJonesP 1 Reply Last reply Reply Quote 0
                      • PeterJonesP
                        PeterJones @ImJohnFolks
                        last edited by PeterJones

                        @ImJohnFolks said in Issues Running Python Scripts in Batch File:

                        With your help, (its took me around 4 hours of just F’ing around) I’ve managed to make some progress on my PythonScript within Notepad++.

                        If you mean you spent a total of 4 hours on all the aspects of the script, including the research and starting from the example, and incorporating our feedback : that’s actually pretty good, considering how new you are to Python and coding in general – congratulations, such effort is to be commended. (Put it in perspective: universities offer semester-long “introduction to Python” classes. In such a class, you might not even have defined one function yet in the first week, let alone the first four hours of class and homework, because they’re still working on variables and for-loops for the first few classes. So you’re doing great)

                        1 Reply Last reply Reply Quote 2
                        • First post
                          Last post
                        The Community of users of the Notepad++ text editor.
                        Powered by NodeBB | Contributors