Change hardcoded values in python 3












0















I would like to change hardcoded values in my code. I would like the code to replace and change hardcoded values based on the number of times it runs. Beginning with:



x=1


The next time, after I run it, in the code itself, I would like to see in the code editor:



x=2


It will automatically change the values of the code without human input, so the third time its run:



x=3


And this is all done just by the script running, no human interaction whatsoever. Is there an easy way?










share|improve this question

























  • One option would be to open in write mode your .py file at the end of your script, find the line you want to modify and replace the value.

    – Patol75
    Nov 20 '18 at 7:49






  • 2





    Possible, of course - most things are. Desirable? Not really. If this value needs to persist across runs, then look at storing it in a file which you can load from your script each time.

    – SiHa
    Nov 20 '18 at 7:50











  • Sure they are possible, but is there an easy way? I would like the values to be dynamic , like that 1 become 2. Let me rephrase it

    – Durian Jaykin
    Nov 20 '18 at 7:51


















0















I would like to change hardcoded values in my code. I would like the code to replace and change hardcoded values based on the number of times it runs. Beginning with:



x=1


The next time, after I run it, in the code itself, I would like to see in the code editor:



x=2


It will automatically change the values of the code without human input, so the third time its run:



x=3


And this is all done just by the script running, no human interaction whatsoever. Is there an easy way?










share|improve this question

























  • One option would be to open in write mode your .py file at the end of your script, find the line you want to modify and replace the value.

    – Patol75
    Nov 20 '18 at 7:49






  • 2





    Possible, of course - most things are. Desirable? Not really. If this value needs to persist across runs, then look at storing it in a file which you can load from your script each time.

    – SiHa
    Nov 20 '18 at 7:50











  • Sure they are possible, but is there an easy way? I would like the values to be dynamic , like that 1 become 2. Let me rephrase it

    – Durian Jaykin
    Nov 20 '18 at 7:51
















0












0








0


2






I would like to change hardcoded values in my code. I would like the code to replace and change hardcoded values based on the number of times it runs. Beginning with:



x=1


The next time, after I run it, in the code itself, I would like to see in the code editor:



x=2


It will automatically change the values of the code without human input, so the third time its run:



x=3


And this is all done just by the script running, no human interaction whatsoever. Is there an easy way?










share|improve this question
















I would like to change hardcoded values in my code. I would like the code to replace and change hardcoded values based on the number of times it runs. Beginning with:



x=1


The next time, after I run it, in the code itself, I would like to see in the code editor:



x=2


It will automatically change the values of the code without human input, so the third time its run:



x=3


And this is all done just by the script running, no human interaction whatsoever. Is there an easy way?







python-3.x hardcode






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 9:19









Jebby

1,167618




1,167618










asked Nov 20 '18 at 7:46









Durian JaykinDurian Jaykin

126




126













  • One option would be to open in write mode your .py file at the end of your script, find the line you want to modify and replace the value.

    – Patol75
    Nov 20 '18 at 7:49






  • 2





    Possible, of course - most things are. Desirable? Not really. If this value needs to persist across runs, then look at storing it in a file which you can load from your script each time.

    – SiHa
    Nov 20 '18 at 7:50











  • Sure they are possible, but is there an easy way? I would like the values to be dynamic , like that 1 become 2. Let me rephrase it

    – Durian Jaykin
    Nov 20 '18 at 7:51





















  • One option would be to open in write mode your .py file at the end of your script, find the line you want to modify and replace the value.

    – Patol75
    Nov 20 '18 at 7:49






  • 2





    Possible, of course - most things are. Desirable? Not really. If this value needs to persist across runs, then look at storing it in a file which you can load from your script each time.

    – SiHa
    Nov 20 '18 at 7:50











  • Sure they are possible, but is there an easy way? I would like the values to be dynamic , like that 1 become 2. Let me rephrase it

    – Durian Jaykin
    Nov 20 '18 at 7:51



















One option would be to open in write mode your .py file at the end of your script, find the line you want to modify and replace the value.

– Patol75
Nov 20 '18 at 7:49





One option would be to open in write mode your .py file at the end of your script, find the line you want to modify and replace the value.

– Patol75
Nov 20 '18 at 7:49




2




2





Possible, of course - most things are. Desirable? Not really. If this value needs to persist across runs, then look at storing it in a file which you can load from your script each time.

– SiHa
Nov 20 '18 at 7:50





Possible, of course - most things are. Desirable? Not really. If this value needs to persist across runs, then look at storing it in a file which you can load from your script each time.

– SiHa
Nov 20 '18 at 7:50













Sure they are possible, but is there an easy way? I would like the values to be dynamic , like that 1 become 2. Let me rephrase it

– Durian Jaykin
Nov 20 '18 at 7:51







Sure they are possible, but is there an easy way? I would like the values to be dynamic , like that 1 become 2. Let me rephrase it

– Durian Jaykin
Nov 20 '18 at 7:51














2 Answers
2






active

oldest

votes


















0














You can simply write to a well-defined auxiliary file:



# define storage file path based on script path (__file__)
import os
counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
# start of script - read or initialise counter
try:
with open(counter_path, 'r') as count_in:
counter = int(count_in.read())
except FileNotFoundError:
counter = 0

print('counter =', counter)

# end of script - write new counter
with open(counter_path, 'w') as count_out:
count_out.write(str(counter + 1))


This will store an auxiliary file next to your script, which contains the counter verbatim.



 $ python3 test.py
counter = 0
$ python3 test.py
counter = 1
$ python3 test.py
counter = 2
$ cat my_counter
3





share|improve this answer

































    2














    Use config parser to store run counter in a file



    import configparser

    config = configparser.ConfigParser()
    config_fn = 'program.ini'

    try:
    config.read(config_fn)
    run_counter = int(config.get('Main', 'run_counter'))
    except configparser.NoSectionError:
    run_counter = 0
    config.add_section('Main')
    config.set('Main', 'run_counter', str(run_counter))
    with open(config_fn, 'w') as config_file:
    config.write(config_file)

    run_counter += 1
    print("Run counter {}".format(run_counter))
    config.set('Main', 'run_counter', str(run_counter))
    with open(config_fn, 'w') as config_file:
    config.write(config_file)





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388362%2fchange-hardcoded-values-in-python-3%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      You can simply write to a well-defined auxiliary file:



      # define storage file path based on script path (__file__)
      import os
      counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
      # start of script - read or initialise counter
      try:
      with open(counter_path, 'r') as count_in:
      counter = int(count_in.read())
      except FileNotFoundError:
      counter = 0

      print('counter =', counter)

      # end of script - write new counter
      with open(counter_path, 'w') as count_out:
      count_out.write(str(counter + 1))


      This will store an auxiliary file next to your script, which contains the counter verbatim.



       $ python3 test.py
      counter = 0
      $ python3 test.py
      counter = 1
      $ python3 test.py
      counter = 2
      $ cat my_counter
      3





      share|improve this answer






























        0














        You can simply write to a well-defined auxiliary file:



        # define storage file path based on script path (__file__)
        import os
        counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
        # start of script - read or initialise counter
        try:
        with open(counter_path, 'r') as count_in:
        counter = int(count_in.read())
        except FileNotFoundError:
        counter = 0

        print('counter =', counter)

        # end of script - write new counter
        with open(counter_path, 'w') as count_out:
        count_out.write(str(counter + 1))


        This will store an auxiliary file next to your script, which contains the counter verbatim.



         $ python3 test.py
        counter = 0
        $ python3 test.py
        counter = 1
        $ python3 test.py
        counter = 2
        $ cat my_counter
        3





        share|improve this answer




























          0












          0








          0







          You can simply write to a well-defined auxiliary file:



          # define storage file path based on script path (__file__)
          import os
          counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
          # start of script - read or initialise counter
          try:
          with open(counter_path, 'r') as count_in:
          counter = int(count_in.read())
          except FileNotFoundError:
          counter = 0

          print('counter =', counter)

          # end of script - write new counter
          with open(counter_path, 'w') as count_out:
          count_out.write(str(counter + 1))


          This will store an auxiliary file next to your script, which contains the counter verbatim.



           $ python3 test.py
          counter = 0
          $ python3 test.py
          counter = 1
          $ python3 test.py
          counter = 2
          $ cat my_counter
          3





          share|improve this answer















          You can simply write to a well-defined auxiliary file:



          # define storage file path based on script path (__file__)
          import os
          counter_path = os.path.join(os.path.dirname(__file__), 'my_counter')
          # start of script - read or initialise counter
          try:
          with open(counter_path, 'r') as count_in:
          counter = int(count_in.read())
          except FileNotFoundError:
          counter = 0

          print('counter =', counter)

          # end of script - write new counter
          with open(counter_path, 'w') as count_out:
          count_out.write(str(counter + 1))


          This will store an auxiliary file next to your script, which contains the counter verbatim.



           $ python3 test.py
          counter = 0
          $ python3 test.py
          counter = 1
          $ python3 test.py
          counter = 2
          $ cat my_counter
          3






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 8:36

























          answered Nov 20 '18 at 8:29









          MisterMiyagiMisterMiyagi

          7,8222444




          7,8222444

























              2














              Use config parser to store run counter in a file



              import configparser

              config = configparser.ConfigParser()
              config_fn = 'program.ini'

              try:
              config.read(config_fn)
              run_counter = int(config.get('Main', 'run_counter'))
              except configparser.NoSectionError:
              run_counter = 0
              config.add_section('Main')
              config.set('Main', 'run_counter', str(run_counter))
              with open(config_fn, 'w') as config_file:
              config.write(config_file)

              run_counter += 1
              print("Run counter {}".format(run_counter))
              config.set('Main', 'run_counter', str(run_counter))
              with open(config_fn, 'w') as config_file:
              config.write(config_file)





              share|improve this answer




























                2














                Use config parser to store run counter in a file



                import configparser

                config = configparser.ConfigParser()
                config_fn = 'program.ini'

                try:
                config.read(config_fn)
                run_counter = int(config.get('Main', 'run_counter'))
                except configparser.NoSectionError:
                run_counter = 0
                config.add_section('Main')
                config.set('Main', 'run_counter', str(run_counter))
                with open(config_fn, 'w') as config_file:
                config.write(config_file)

                run_counter += 1
                print("Run counter {}".format(run_counter))
                config.set('Main', 'run_counter', str(run_counter))
                with open(config_fn, 'w') as config_file:
                config.write(config_file)





                share|improve this answer


























                  2












                  2








                  2







                  Use config parser to store run counter in a file



                  import configparser

                  config = configparser.ConfigParser()
                  config_fn = 'program.ini'

                  try:
                  config.read(config_fn)
                  run_counter = int(config.get('Main', 'run_counter'))
                  except configparser.NoSectionError:
                  run_counter = 0
                  config.add_section('Main')
                  config.set('Main', 'run_counter', str(run_counter))
                  with open(config_fn, 'w') as config_file:
                  config.write(config_file)

                  run_counter += 1
                  print("Run counter {}".format(run_counter))
                  config.set('Main', 'run_counter', str(run_counter))
                  with open(config_fn, 'w') as config_file:
                  config.write(config_file)





                  share|improve this answer













                  Use config parser to store run counter in a file



                  import configparser

                  config = configparser.ConfigParser()
                  config_fn = 'program.ini'

                  try:
                  config.read(config_fn)
                  run_counter = int(config.get('Main', 'run_counter'))
                  except configparser.NoSectionError:
                  run_counter = 0
                  config.add_section('Main')
                  config.set('Main', 'run_counter', str(run_counter))
                  with open(config_fn, 'w') as config_file:
                  config.write(config_file)

                  run_counter += 1
                  print("Run counter {}".format(run_counter))
                  config.set('Main', 'run_counter', str(run_counter))
                  with open(config_fn, 'w') as config_file:
                  config.write(config_file)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 8:03









                  Pawel StradowskiPawel Stradowski

                  19419




                  19419






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388362%2fchange-hardcoded-values-in-python-3%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Guess what letter conforming each word

                      Port of Spain

                      Run scheduled task as local user group (not BUILTIN)