I want to run a python3 script on startup and in an endless loop on my raspberry pi Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Congratulation Joan for 50k!High usage of cpu and ram with while loopWhy are the buttons that I am using with my Pi inverted?Using init.d script to start my python program on startupHow 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?GPIO unexpected behaviour after 10 hours of running python scriptHow to resolve “RuntimeError: Unable to export GPIO. Try to run as root!”?How to start and stop python script using buttonRun a system startup script after network and DNS resolution are available

Can an alien society believe that their star system is the universe?

ArcGIS Pro Python arcpy.CreatePersonalGDB_management

Find 108 by using 3,4,6

AppleTVs create a chatty alternate WiFi network

What does it mean that physics no longer uses mechanical models to describe phenomena?

If Windows 7 doesn't support WSL, then what does Linux subsystem option mean?

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?

How to write the following sign?

How to compare two different files line by line in unix?

Most bit efficient text communication method?

Trademark violation for app?

Disembodied hand growing fangs

Sum letters are not two different

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

Do wooden building fires get hotter than 600°C?

What do you call the main part of a joke?

How does light 'choose' between wave and particle behaviour?

Drawing without replacement: why is the order of draw irrelevant?

Should I follow up with an employee I believe overracted to a mistake I made?

What initially awakened the Balrog?

Why should I vote and accept answers?

SF book about people trapped in a series of worlds they imagine

Generate an RGB colour grid

Multiple OR (||) Conditions in If Statement



I want to run a python3 script on startup and in an endless loop on my raspberry pi



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Congratulation Joan for 50k!High usage of cpu and ram with while loopWhy are the buttons that I am using with my Pi inverted?Using init.d script to start my python program on startupHow 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?GPIO unexpected behaviour after 10 hours of running python scriptHow to resolve “RuntimeError: Unable to export GPIO. Try to run as root!”?How to start and stop python script using buttonRun a system startup script after network and DNS resolution are available



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








2















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



I want to automate the process and run the script on startup and 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 pi and whenever the button is pressed the script should run using python3.



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









share




























    2















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



    I want to automate the process and run the script on startup and 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 pi and whenever the button is pressed the script should run using python3.



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









    share
























      2












      2








      2


      1






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



      I want to automate the process and run the script on startup and 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 pi and whenever the button is pressed the script should run using python3.



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









      share














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



      I want to automate the process and run the script on startup and 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 pi and whenever the button is pressed the script should run using python3.



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







      raspbian pi-3 gpio python-3 init.d





      share












      share










      share



      share










      asked 9 hours ago









      Adnan FarooquiAdnan Farooqui

      265




      265




















          2 Answers
          2






          active

          oldest

          votes


















          2














          We were able to use Supervisor (http://supervisord.org/
          ) to successfully have a python script run in the background on boot.



          Tutorial I Used to set it up:
          https://serversforhackers.com/c/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 config info



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


          Enter the config info 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 config 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










          New contributor




          AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.



























            2














            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 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-python3-script-on-startup-and-in-an-endless-loop-on-my-raspberry%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









              2














              We were able to use Supervisor (http://supervisord.org/
              ) to successfully have a python script run in the background on boot.



              Tutorial I Used to set it up:
              https://serversforhackers.com/c/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 config info



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


              Enter the config info 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 config 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










              New contributor




              AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.
























                2














                We were able to use Supervisor (http://supervisord.org/
                ) to successfully have a python script run in the background on boot.



                Tutorial I Used to set it up:
                https://serversforhackers.com/c/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 config info



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


                Enter the config info 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 config 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










                New contributor




                AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






















                  2












                  2








                  2







                  We were able to use Supervisor (http://supervisord.org/
                  ) to successfully have a python script run in the background on boot.



                  Tutorial I Used to set it up:
                  https://serversforhackers.com/c/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 config info



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


                  Enter the config info 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 config 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










                  New contributor




                  AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.










                  We were able to use Supervisor (http://supervisord.org/
                  ) to successfully have a python script run in the background on boot.



                  Tutorial I Used to set it up:
                  https://serversforhackers.com/c/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 config info



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


                  Enter the config info 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 config 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










                  New contributor




                  AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.








                  share


                  share








                  edited 7 hours ago





















                  New contributor




                  AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  answered 8 hours ago









                  AaronDoesDevAaronDoesDev

                  212




                  212




                  New contributor




                  AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  New contributor





                  AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  AaronDoesDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.























                      2














                      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














                        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












                          2








                          2







                          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 4 hours ago









                          IngoIngo

                          9,4093952




                          9,4093952



























                              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-python3-script-on-startup-and-in-an-endless-loop-on-my-raspberry%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

                              How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                              Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                              Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр