python3 subprocess pip “ImportError: cannot import name main” in terminal











up vote
0
down vote

favorite












I created a script (see below) to upgrade all my pip packages. I successfully executed my script via idle3, i.e. open the script using idle3 and pressing F5 to run the script as a module. However, I am not able to execute it in the terminal; got the below error. How do I overcome this error? Why does the import error happen in terminal but not in idle3?



$ python3 -m upgrade_pip_packages 
====================================================
UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:
====================================================
Traceback (most recent call last):
File "/usr/bin/pip", line 9, in <module>
from pip import main
ImportError: cannot import name main
ERROR: Command 'pip list' returned non-zero exit status 1


My script : upgrade_pip_packages.py



#!/bin/python3
import subprocess
from pprint import pprint


def get_pkgs():
try:
cmd = 'pip list'
completed = subprocess.run( cmd, shell=True, check=True,
stdout=subprocess.PIPE )
except subprocess.CalledProcessError as err:
print( 'ERROR:', err )
else:
for line in completed.stdout.decode('utf-8').splitlines()[2:]:
yield line


def update_pkgs(piplist):
npackages = 0
nupgrades = 0
nerrors = 0
upgradelist =
errorlist =
for i in piplist:
npackages += 1
pkgname, ver = i.split()
print('n',pkgname)
try:
cmd = 'pip install --user {} --upgrade'.format(pkgname)
completed = subprocess.run( cmd, shell=True, check=True,
stdout=subprocess.PIPE )
except subprocess.CalledProcessError as err:
nerrors += 1
errorlist.append(pkgname)
print( 'ERROR: {}'.format(err) )
else:
for line in completed.stdout.decode('utf-8').splitlines():
print(line)
if 'Successfully installed' in line:
nupgrades +=1
upgradelist.append(pkgname)
return npackages, nupgrades, nerrors, upgradelist, errorlist


def main():
print('====================================================')
print('UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:')
print('====================================================')
pip_pkgs = get_pkgs() # created a generator
npackages, nupgrades, nerrors, upgradelist, errorlist
= update_pkgs(pip_pkgs)
print('nNo. of --user pip packages = {}'.format(npackages))
print('No. of upgrades = {}'.format(nupgrades))
print('No. of upgrade errors = {}'.format(nerrors))
if upgradelist:
print('Package(s) upgraded:')
pprint(upgradelist)
if errorlist:
print('Package(s) with upgrade error:')
pprint(errorlist)
print()


if __name__ == '__main__':
main()









share|improve this question




























    up vote
    0
    down vote

    favorite












    I created a script (see below) to upgrade all my pip packages. I successfully executed my script via idle3, i.e. open the script using idle3 and pressing F5 to run the script as a module. However, I am not able to execute it in the terminal; got the below error. How do I overcome this error? Why does the import error happen in terminal but not in idle3?



    $ python3 -m upgrade_pip_packages 
    ====================================================
    UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:
    ====================================================
    Traceback (most recent call last):
    File "/usr/bin/pip", line 9, in <module>
    from pip import main
    ImportError: cannot import name main
    ERROR: Command 'pip list' returned non-zero exit status 1


    My script : upgrade_pip_packages.py



    #!/bin/python3
    import subprocess
    from pprint import pprint


    def get_pkgs():
    try:
    cmd = 'pip list'
    completed = subprocess.run( cmd, shell=True, check=True,
    stdout=subprocess.PIPE )
    except subprocess.CalledProcessError as err:
    print( 'ERROR:', err )
    else:
    for line in completed.stdout.decode('utf-8').splitlines()[2:]:
    yield line


    def update_pkgs(piplist):
    npackages = 0
    nupgrades = 0
    nerrors = 0
    upgradelist =
    errorlist =
    for i in piplist:
    npackages += 1
    pkgname, ver = i.split()
    print('n',pkgname)
    try:
    cmd = 'pip install --user {} --upgrade'.format(pkgname)
    completed = subprocess.run( cmd, shell=True, check=True,
    stdout=subprocess.PIPE )
    except subprocess.CalledProcessError as err:
    nerrors += 1
    errorlist.append(pkgname)
    print( 'ERROR: {}'.format(err) )
    else:
    for line in completed.stdout.decode('utf-8').splitlines():
    print(line)
    if 'Successfully installed' in line:
    nupgrades +=1
    upgradelist.append(pkgname)
    return npackages, nupgrades, nerrors, upgradelist, errorlist


    def main():
    print('====================================================')
    print('UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:')
    print('====================================================')
    pip_pkgs = get_pkgs() # created a generator
    npackages, nupgrades, nerrors, upgradelist, errorlist
    = update_pkgs(pip_pkgs)
    print('nNo. of --user pip packages = {}'.format(npackages))
    print('No. of upgrades = {}'.format(nupgrades))
    print('No. of upgrade errors = {}'.format(nerrors))
    if upgradelist:
    print('Package(s) upgraded:')
    pprint(upgradelist)
    if errorlist:
    print('Package(s) with upgrade error:')
    pprint(errorlist)
    print()


    if __name__ == '__main__':
    main()









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I created a script (see below) to upgrade all my pip packages. I successfully executed my script via idle3, i.e. open the script using idle3 and pressing F5 to run the script as a module. However, I am not able to execute it in the terminal; got the below error. How do I overcome this error? Why does the import error happen in terminal but not in idle3?



      $ python3 -m upgrade_pip_packages 
      ====================================================
      UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:
      ====================================================
      Traceback (most recent call last):
      File "/usr/bin/pip", line 9, in <module>
      from pip import main
      ImportError: cannot import name main
      ERROR: Command 'pip list' returned non-zero exit status 1


      My script : upgrade_pip_packages.py



      #!/bin/python3
      import subprocess
      from pprint import pprint


      def get_pkgs():
      try:
      cmd = 'pip list'
      completed = subprocess.run( cmd, shell=True, check=True,
      stdout=subprocess.PIPE )
      except subprocess.CalledProcessError as err:
      print( 'ERROR:', err )
      else:
      for line in completed.stdout.decode('utf-8').splitlines()[2:]:
      yield line


      def update_pkgs(piplist):
      npackages = 0
      nupgrades = 0
      nerrors = 0
      upgradelist =
      errorlist =
      for i in piplist:
      npackages += 1
      pkgname, ver = i.split()
      print('n',pkgname)
      try:
      cmd = 'pip install --user {} --upgrade'.format(pkgname)
      completed = subprocess.run( cmd, shell=True, check=True,
      stdout=subprocess.PIPE )
      except subprocess.CalledProcessError as err:
      nerrors += 1
      errorlist.append(pkgname)
      print( 'ERROR: {}'.format(err) )
      else:
      for line in completed.stdout.decode('utf-8').splitlines():
      print(line)
      if 'Successfully installed' in line:
      nupgrades +=1
      upgradelist.append(pkgname)
      return npackages, nupgrades, nerrors, upgradelist, errorlist


      def main():
      print('====================================================')
      print('UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:')
      print('====================================================')
      pip_pkgs = get_pkgs() # created a generator
      npackages, nupgrades, nerrors, upgradelist, errorlist
      = update_pkgs(pip_pkgs)
      print('nNo. of --user pip packages = {}'.format(npackages))
      print('No. of upgrades = {}'.format(nupgrades))
      print('No. of upgrade errors = {}'.format(nerrors))
      if upgradelist:
      print('Package(s) upgraded:')
      pprint(upgradelist)
      if errorlist:
      print('Package(s) with upgrade error:')
      pprint(errorlist)
      print()


      if __name__ == '__main__':
      main()









      share|improve this question















      I created a script (see below) to upgrade all my pip packages. I successfully executed my script via idle3, i.e. open the script using idle3 and pressing F5 to run the script as a module. However, I am not able to execute it in the terminal; got the below error. How do I overcome this error? Why does the import error happen in terminal but not in idle3?



      $ python3 -m upgrade_pip_packages 
      ====================================================
      UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:
      ====================================================
      Traceback (most recent call last):
      File "/usr/bin/pip", line 9, in <module>
      from pip import main
      ImportError: cannot import name main
      ERROR: Command 'pip list' returned non-zero exit status 1


      My script : upgrade_pip_packages.py



      #!/bin/python3
      import subprocess
      from pprint import pprint


      def get_pkgs():
      try:
      cmd = 'pip list'
      completed = subprocess.run( cmd, shell=True, check=True,
      stdout=subprocess.PIPE )
      except subprocess.CalledProcessError as err:
      print( 'ERROR:', err )
      else:
      for line in completed.stdout.decode('utf-8').splitlines()[2:]:
      yield line


      def update_pkgs(piplist):
      npackages = 0
      nupgrades = 0
      nerrors = 0
      upgradelist =
      errorlist =
      for i in piplist:
      npackages += 1
      pkgname, ver = i.split()
      print('n',pkgname)
      try:
      cmd = 'pip install --user {} --upgrade'.format(pkgname)
      completed = subprocess.run( cmd, shell=True, check=True,
      stdout=subprocess.PIPE )
      except subprocess.CalledProcessError as err:
      nerrors += 1
      errorlist.append(pkgname)
      print( 'ERROR: {}'.format(err) )
      else:
      for line in completed.stdout.decode('utf-8').splitlines():
      print(line)
      if 'Successfully installed' in line:
      nupgrades +=1
      upgradelist.append(pkgname)
      return npackages, nupgrades, nerrors, upgradelist, errorlist


      def main():
      print('====================================================')
      print('UPGRADING ALL --USER PIP PACKAGES TO LATEST VERSION:')
      print('====================================================')
      pip_pkgs = get_pkgs() # created a generator
      npackages, nupgrades, nerrors, upgradelist, errorlist
      = update_pkgs(pip_pkgs)
      print('nNo. of --user pip packages = {}'.format(npackages))
      print('No. of upgrades = {}'.format(nupgrades))
      print('No. of upgrade errors = {}'.format(nerrors))
      if upgradelist:
      print('Package(s) upgraded:')
      pprint(upgradelist)
      if errorlist:
      print('Package(s) with upgrade error:')
      pprint(errorlist)
      print()


      if __name__ == '__main__':
      main()






      python terminal pip subprocess ubuntu-16.04






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 1:12

























      asked Nov 10 at 14:53









      Sun Bear

      1,517729




      1,517729
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Final upgrade_pip_packages.py.



          I found the answer to my question. Essentially, my script had to:



          import sys


          and make the following amendments:



          cmd = [sys.executable, '-m', 'pip', 'list'] #Change here
          completed = subprocess.run( cmd,
          #shell=True, #switch this off
          check=True,
          stdout=subprocess.PIPE )


          and



          cmd = [sys.executable, '-m', 'pip', 'install', '--user', pkgname, '--upgrade'] #Change here
          completed = subprocess.run( cmd,
          #shell=True, #switch this off
          check=True,
          stdout=subprocess.PIPE )


          PyPA documentation explanation:




          It’s recommended to write {sys.executable} rather than plain python in
          order to ensure that commands are run in the Python installation
          matching the currently running notebook (which may not be the same
          Python installation that the python command refers to).




          $ pip --version
          pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)
          $ pip3 --version
          pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)





          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',
            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%2f53240133%2fpython3-subprocess-pip-importerror-cannot-import-name-main-in-terminal%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            Final upgrade_pip_packages.py.



            I found the answer to my question. Essentially, my script had to:



            import sys


            and make the following amendments:



            cmd = [sys.executable, '-m', 'pip', 'list'] #Change here
            completed = subprocess.run( cmd,
            #shell=True, #switch this off
            check=True,
            stdout=subprocess.PIPE )


            and



            cmd = [sys.executable, '-m', 'pip', 'install', '--user', pkgname, '--upgrade'] #Change here
            completed = subprocess.run( cmd,
            #shell=True, #switch this off
            check=True,
            stdout=subprocess.PIPE )


            PyPA documentation explanation:




            It’s recommended to write {sys.executable} rather than plain python in
            order to ensure that commands are run in the Python installation
            matching the currently running notebook (which may not be the same
            Python installation that the python command refers to).




            $ pip --version
            pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)
            $ pip3 --version
            pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)





            share|improve this answer



























              up vote
              0
              down vote



              accepted










              Final upgrade_pip_packages.py.



              I found the answer to my question. Essentially, my script had to:



              import sys


              and make the following amendments:



              cmd = [sys.executable, '-m', 'pip', 'list'] #Change here
              completed = subprocess.run( cmd,
              #shell=True, #switch this off
              check=True,
              stdout=subprocess.PIPE )


              and



              cmd = [sys.executable, '-m', 'pip', 'install', '--user', pkgname, '--upgrade'] #Change here
              completed = subprocess.run( cmd,
              #shell=True, #switch this off
              check=True,
              stdout=subprocess.PIPE )


              PyPA documentation explanation:




              It’s recommended to write {sys.executable} rather than plain python in
              order to ensure that commands are run in the Python installation
              matching the currently running notebook (which may not be the same
              Python installation that the python command refers to).




              $ pip --version
              pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)
              $ pip3 --version
              pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)





              share|improve this answer

























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                Final upgrade_pip_packages.py.



                I found the answer to my question. Essentially, my script had to:



                import sys


                and make the following amendments:



                cmd = [sys.executable, '-m', 'pip', 'list'] #Change here
                completed = subprocess.run( cmd,
                #shell=True, #switch this off
                check=True,
                stdout=subprocess.PIPE )


                and



                cmd = [sys.executable, '-m', 'pip', 'install', '--user', pkgname, '--upgrade'] #Change here
                completed = subprocess.run( cmd,
                #shell=True, #switch this off
                check=True,
                stdout=subprocess.PIPE )


                PyPA documentation explanation:




                It’s recommended to write {sys.executable} rather than plain python in
                order to ensure that commands are run in the Python installation
                matching the currently running notebook (which may not be the same
                Python installation that the python command refers to).




                $ pip --version
                pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)
                $ pip3 --version
                pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)





                share|improve this answer














                Final upgrade_pip_packages.py.



                I found the answer to my question. Essentially, my script had to:



                import sys


                and make the following amendments:



                cmd = [sys.executable, '-m', 'pip', 'list'] #Change here
                completed = subprocess.run( cmd,
                #shell=True, #switch this off
                check=True,
                stdout=subprocess.PIPE )


                and



                cmd = [sys.executable, '-m', 'pip', 'install', '--user', pkgname, '--upgrade'] #Change here
                completed = subprocess.run( cmd,
                #shell=True, #switch this off
                check=True,
                stdout=subprocess.PIPE )


                PyPA documentation explanation:




                It’s recommended to write {sys.executable} rather than plain python in
                order to ensure that commands are run in the Python installation
                matching the currently running notebook (which may not be the same
                Python installation that the python command refers to).




                $ pip --version
                pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)
                $ pip3 --version
                pip 18.1 from ~/.local/lib/python3.5/site-packages/pip (python 3.5)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 10 at 19:33

























                answered Nov 10 at 17:46









                Sun Bear

                1,517729




                1,517729






























                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53240133%2fpython3-subprocess-pip-importerror-cannot-import-name-main-in-terminal%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

                    Florida Star v. B. J. F.

                    Error while running script in elastic search , gateway timeout

                    Adding quotations to stringified JSON object values