I want to run a Python 3 script on startup and in an endless loop on my Raspberry PiHigh usage of cpu and ram with while loopWhy are the buttons that I am using with my Pi inverted?How can I get my init.d script to be the last startup item on runlevel 4?Why won't `gpio` work from an init script?How to run a Python script on a raspberry pi via webserver?Activate virtual environment and run python script on RPi startupGPIO unexpected behaviour after 10 hours of running python scriptHow to resolve “RuntimeError: Unable to export GPIO. Try to run as root!”?RPI Run a Python script fan speed control while loop until shutdownHow to start and stop python script using button

Retract an already submitted recommendation letter (written for an undergrad student)

Is there really no use for MD5 anymore?

As an international instructor, should I openly talk about my accent?

Drawing a german abacus as in the books of Adam Ries

std::unique_ptr of base class holding reference of derived class does not show warning in gcc compiler while naked pointer shows it. Why?

Apply a different color ramp to subset of categorized symbols in QGIS?

Why did Rep. Omar conclude her criticism of US troops with the phrase "NotTodaySatan"?

Multiple fireplaces in an apartment building?

What is the best way to deal with NPC-NPC combat?

Mistake in years of experience in resume?

How important is it that $TERM is correct?

Multiple options vs single option UI

Will I lose my paid in full property

Why do games have consumables?

Philosophical question on logistic regression: why isn't the optimal threshold value trained?

Creating a chemical industry from a medieval tech level without petroleum

Find the identical rows in a matrix

Combinatorics problem, right solution?

"The cow" OR "a cow" OR "cows" in this context

What *exactly* is electrical current, voltage, and resistance?

Who's the random kid standing in the gathering at the end?

A ​Note ​on ​N!

How much of a wave function must reside inside event horizon for it to be consumed by the black hole?

Check if a string is entirely made of the same substring



I want to run a Python 3 script on startup and in an endless loop on my Raspberry Pi


High usage of cpu and ram with while loopWhy are the buttons that I am using with my Pi inverted?How can I get my init.d script to be the last startup item on runlevel 4?Why won't `gpio` work from an init script?How to run a Python script on a raspberry pi via webserver?Activate virtual environment and run python script on RPi startupGPIO unexpected behaviour after 10 hours of running python scriptHow to resolve “RuntimeError: Unable to export GPIO. Try to run as root!”?RPI Run a Python script fan speed control while loop until shutdownHow to start and stop python script using button






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















I have created a smart vending machine using my Raspberry Pi. For now, I open the Raspberry Pi using SSH and run the script manually for every transaction.



I want to automate the process and run the script on startup. After execution I want it to run again in a loop till shut down.



If possible I can also map it to a physical button which I connect to the Raspberry Pi and whenever the button is pressed the script should run using Python 3.



How can I possibly do any of the above two things?










share|improve this question






























    3















    I have created a smart vending machine using my Raspberry Pi. For now, I open the Raspberry Pi using SSH and run the script manually for every transaction.



    I want to automate the process and run the script on startup. After execution I want it to run again in a loop till shut down.



    If possible I can also map it to a physical button which I connect to the Raspberry Pi and whenever the button is pressed the script should run using Python 3.



    How can I possibly do any of the above two things?










    share|improve this question


























      3












      3








      3


      5






      I have created a smart vending machine using my Raspberry Pi. For now, I open the Raspberry Pi using SSH and run the script manually for every transaction.



      I want to automate the process and run the script on startup. After execution I want it to run again in a loop till shut down.



      If possible I can also map it to a physical button which I connect to the Raspberry Pi and whenever the button is pressed the script should run using Python 3.



      How can I possibly do any of the above two things?










      share|improve this question
















      I have created a smart vending machine using my Raspberry Pi. For now, I open the Raspberry Pi using SSH and run the script manually for every transaction.



      I want to automate the process and run the script on startup. After execution I want it to run again in a loop till shut down.



      If possible I can also map it to a physical button which I connect to the Raspberry Pi and whenever the button is pressed the script should run using Python 3.



      How can I possibly do any of the above two things?







      raspbian pi-3 gpio python-3 init.d






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 19 at 2:09









      Peter Mortensen

      1,82311117




      1,82311117










      asked Apr 18 at 13:36









      Adnan FarooquiAdnan Farooqui

      316




      316




















          2 Answers
          2






          active

          oldest

          votes


















          4














          Your script is a typical use of a service. Usually a service is started once and then it is running in background until it is stopped by the service manager. The service manager can restart a script but it isn't made to be used for loops because it is working on system level with logging and dependency checking and all to manage services.



          So first you should program the endless loop within the script. Within this loop you can also check if the button is pressed and do what is needed then.



          The default init system and service manager is systemd on Raspbian and it manages services with Unit files. So you should start with a simple Unit file for your service with:



          rpi ~$ sudo systemctl --full --force edit myscript.service


          In the empty editor insert these statements, save them and quit the editor:



          [Unit]
          Description=My python3 script
          After=multi-user.target

          [Service]
          ExecStart=/full/path/to/myscript.py

          [Install]
          WantedBy=multi-user.target


          Then enable it to be started on boot up:



          rpi ~$ sudo systemctl enable myscript.service


          You can look at it's status with:



          rpi ~$ systemctl status myscript.service


          It may be that it isn't running on the first attempt because your script needs some environment conditions. We will see. For some environment settings you can look at man systemd.exec.






          share|improve this answer






























            2














            We were able to use Supervisor to successfully have a Python script run in the background on boot.



            Tutorial I Used to set it up: Monitoring Processes with Supervisord



            Supervisor runs as a service, and you have a configuration file where you set up your scripts that you want it to run:



            [program:your_script_name]
            command=python3 your_script_name.py
            directory=/your/file/location/here
            autostart=true
            autorestart=true


            You could either have Supervisor run your vending machine scripts on start up or start a script that is waiting for your button press which would then launch your main vending machine script.



            Steps: (Using terminal)



            sudo apt-get install -y supervisor


            Start the service



            sudo service supervisor start


            Create your configuration information:



            sudo nano /etc/supervisor/conf.d/yourscriptname.conf


            Enter the configuration information and save the file:



            [program:your_script_name]
            command=python3 your_script_name.py
            directory=/your/file/location/here
            autostart=true
            autorestart=true


            Update Supervisor to include your new configuration file:



            supervisorctl reread
            supervisorctl update


            See if your service started:



            supervisorctl


            Start and stop the your script from running:



            supervisorctl stop your_script_name
            supervisorctl start your_script_name





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              return StackExchange.using("schematics", function ()
              StackExchange.schematics.init();
              );
              , "cicuitlab");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "447"
              ;
              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: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              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%2fraspberrypi.stackexchange.com%2fquestions%2f96673%2fi-want-to-run-a-python-3-script-on-startup-and-in-an-endless-loop-on-my-raspberr%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









              4














              Your script is a typical use of a service. Usually a service is started once and then it is running in background until it is stopped by the service manager. The service manager can restart a script but it isn't made to be used for loops because it is working on system level with logging and dependency checking and all to manage services.



              So first you should program the endless loop within the script. Within this loop you can also check if the button is pressed and do what is needed then.



              The default init system and service manager is systemd on Raspbian and it manages services with Unit files. So you should start with a simple Unit file for your service with:



              rpi ~$ sudo systemctl --full --force edit myscript.service


              In the empty editor insert these statements, save them and quit the editor:



              [Unit]
              Description=My python3 script
              After=multi-user.target

              [Service]
              ExecStart=/full/path/to/myscript.py

              [Install]
              WantedBy=multi-user.target


              Then enable it to be started on boot up:



              rpi ~$ sudo systemctl enable myscript.service


              You can look at it's status with:



              rpi ~$ systemctl status myscript.service


              It may be that it isn't running on the first attempt because your script needs some environment conditions. We will see. For some environment settings you can look at man systemd.exec.






              share|improve this answer



























                4














                Your script is a typical use of a service. Usually a service is started once and then it is running in background until it is stopped by the service manager. The service manager can restart a script but it isn't made to be used for loops because it is working on system level with logging and dependency checking and all to manage services.



                So first you should program the endless loop within the script. Within this loop you can also check if the button is pressed and do what is needed then.



                The default init system and service manager is systemd on Raspbian and it manages services with Unit files. So you should start with a simple Unit file for your service with:



                rpi ~$ sudo systemctl --full --force edit myscript.service


                In the empty editor insert these statements, save them and quit the editor:



                [Unit]
                Description=My python3 script
                After=multi-user.target

                [Service]
                ExecStart=/full/path/to/myscript.py

                [Install]
                WantedBy=multi-user.target


                Then enable it to be started on boot up:



                rpi ~$ sudo systemctl enable myscript.service


                You can look at it's status with:



                rpi ~$ systemctl status myscript.service


                It may be that it isn't running on the first attempt because your script needs some environment conditions. We will see. For some environment settings you can look at man systemd.exec.






                share|improve this answer

























                  4












                  4








                  4







                  Your script is a typical use of a service. Usually a service is started once and then it is running in background until it is stopped by the service manager. The service manager can restart a script but it isn't made to be used for loops because it is working on system level with logging and dependency checking and all to manage services.



                  So first you should program the endless loop within the script. Within this loop you can also check if the button is pressed and do what is needed then.



                  The default init system and service manager is systemd on Raspbian and it manages services with Unit files. So you should start with a simple Unit file for your service with:



                  rpi ~$ sudo systemctl --full --force edit myscript.service


                  In the empty editor insert these statements, save them and quit the editor:



                  [Unit]
                  Description=My python3 script
                  After=multi-user.target

                  [Service]
                  ExecStart=/full/path/to/myscript.py

                  [Install]
                  WantedBy=multi-user.target


                  Then enable it to be started on boot up:



                  rpi ~$ sudo systemctl enable myscript.service


                  You can look at it's status with:



                  rpi ~$ systemctl status myscript.service


                  It may be that it isn't running on the first attempt because your script needs some environment conditions. We will see. For some environment settings you can look at man systemd.exec.






                  share|improve this answer













                  Your script is a typical use of a service. Usually a service is started once and then it is running in background until it is stopped by the service manager. The service manager can restart a script but it isn't made to be used for loops because it is working on system level with logging and dependency checking and all to manage services.



                  So first you should program the endless loop within the script. Within this loop you can also check if the button is pressed and do what is needed then.



                  The default init system and service manager is systemd on Raspbian and it manages services with Unit files. So you should start with a simple Unit file for your service with:



                  rpi ~$ sudo systemctl --full --force edit myscript.service


                  In the empty editor insert these statements, save them and quit the editor:



                  [Unit]
                  Description=My python3 script
                  After=multi-user.target

                  [Service]
                  ExecStart=/full/path/to/myscript.py

                  [Install]
                  WantedBy=multi-user.target


                  Then enable it to be started on boot up:



                  rpi ~$ sudo systemctl enable myscript.service


                  You can look at it's status with:



                  rpi ~$ systemctl status myscript.service


                  It may be that it isn't running on the first attempt because your script needs some environment conditions. We will see. For some environment settings you can look at man systemd.exec.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 18 at 18:45









                  IngoIngo

                  9,5883953




                  9,5883953























                      2














                      We were able to use Supervisor to successfully have a Python script run in the background on boot.



                      Tutorial I Used to set it up: Monitoring Processes with Supervisord



                      Supervisor runs as a service, and you have a configuration file where you set up your scripts that you want it to run:



                      [program:your_script_name]
                      command=python3 your_script_name.py
                      directory=/your/file/location/here
                      autostart=true
                      autorestart=true


                      You could either have Supervisor run your vending machine scripts on start up or start a script that is waiting for your button press which would then launch your main vending machine script.



                      Steps: (Using terminal)



                      sudo apt-get install -y supervisor


                      Start the service



                      sudo service supervisor start


                      Create your configuration information:



                      sudo nano /etc/supervisor/conf.d/yourscriptname.conf


                      Enter the configuration information and save the file:



                      [program:your_script_name]
                      command=python3 your_script_name.py
                      directory=/your/file/location/here
                      autostart=true
                      autorestart=true


                      Update Supervisor to include your new configuration file:



                      supervisorctl reread
                      supervisorctl update


                      See if your service started:



                      supervisorctl


                      Start and stop the your script from running:



                      supervisorctl stop your_script_name
                      supervisorctl start your_script_name





                      share|improve this answer





























                        2














                        We were able to use Supervisor to successfully have a Python script run in the background on boot.



                        Tutorial I Used to set it up: Monitoring Processes with Supervisord



                        Supervisor runs as a service, and you have a configuration file where you set up your scripts that you want it to run:



                        [program:your_script_name]
                        command=python3 your_script_name.py
                        directory=/your/file/location/here
                        autostart=true
                        autorestart=true


                        You could either have Supervisor run your vending machine scripts on start up or start a script that is waiting for your button press which would then launch your main vending machine script.



                        Steps: (Using terminal)



                        sudo apt-get install -y supervisor


                        Start the service



                        sudo service supervisor start


                        Create your configuration information:



                        sudo nano /etc/supervisor/conf.d/yourscriptname.conf


                        Enter the configuration information and save the file:



                        [program:your_script_name]
                        command=python3 your_script_name.py
                        directory=/your/file/location/here
                        autostart=true
                        autorestart=true


                        Update Supervisor to include your new configuration file:



                        supervisorctl reread
                        supervisorctl update


                        See if your service started:



                        supervisorctl


                        Start and stop the your script from running:



                        supervisorctl stop your_script_name
                        supervisorctl start your_script_name





                        share|improve this answer



























                          2












                          2








                          2







                          We were able to use Supervisor to successfully have a Python script run in the background on boot.



                          Tutorial I Used to set it up: Monitoring Processes with Supervisord



                          Supervisor runs as a service, and you have a configuration file where you set up your scripts that you want it to run:



                          [program:your_script_name]
                          command=python3 your_script_name.py
                          directory=/your/file/location/here
                          autostart=true
                          autorestart=true


                          You could either have Supervisor run your vending machine scripts on start up or start a script that is waiting for your button press which would then launch your main vending machine script.



                          Steps: (Using terminal)



                          sudo apt-get install -y supervisor


                          Start the service



                          sudo service supervisor start


                          Create your configuration information:



                          sudo nano /etc/supervisor/conf.d/yourscriptname.conf


                          Enter the configuration information and save the file:



                          [program:your_script_name]
                          command=python3 your_script_name.py
                          directory=/your/file/location/here
                          autostart=true
                          autorestart=true


                          Update Supervisor to include your new configuration file:



                          supervisorctl reread
                          supervisorctl update


                          See if your service started:



                          supervisorctl


                          Start and stop the your script from running:



                          supervisorctl stop your_script_name
                          supervisorctl start your_script_name





                          share|improve this answer















                          We were able to use Supervisor to successfully have a Python script run in the background on boot.



                          Tutorial I Used to set it up: Monitoring Processes with Supervisord



                          Supervisor runs as a service, and you have a configuration file where you set up your scripts that you want it to run:



                          [program:your_script_name]
                          command=python3 your_script_name.py
                          directory=/your/file/location/here
                          autostart=true
                          autorestart=true


                          You could either have Supervisor run your vending machine scripts on start up or start a script that is waiting for your button press which would then launch your main vending machine script.



                          Steps: (Using terminal)



                          sudo apt-get install -y supervisor


                          Start the service



                          sudo service supervisor start


                          Create your configuration information:



                          sudo nano /etc/supervisor/conf.d/yourscriptname.conf


                          Enter the configuration information and save the file:



                          [program:your_script_name]
                          command=python3 your_script_name.py
                          directory=/your/file/location/here
                          autostart=true
                          autorestart=true


                          Update Supervisor to include your new configuration file:



                          supervisorctl reread
                          supervisorctl update


                          See if your service started:



                          supervisorctl


                          Start and stop the your script from running:



                          supervisorctl stop your_script_name
                          supervisorctl start your_script_name






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Apr 19 at 9:26









                          Peter Mortensen

                          1,82311117




                          1,82311117










                          answered Apr 18 at 14:20









                          AaronDoesDevAaronDoesDev

                          212




                          212



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Raspberry Pi Stack Exchange!


                              • 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%2fraspberrypi.stackexchange.com%2fquestions%2f96673%2fi-want-to-run-a-python-3-script-on-startup-and-in-an-endless-loop-on-my-raspberr%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

                              Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

                              Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                              What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company