Python AttributeError: 'Module' object has no attribute 'STARTF_USESHOWINDOW'

Scholars have to be ambitious to learn, not to learn, not to learn, not to become a broad talent, not to aspire to become a scholar. —— Zhuge Liang
Du Jinyang

Today's new colleague's installation environment encountered a puzzling problem:

AttributeError: 'Module' object has no attribute 'STARTF_USESHOWINDOW' 

It seems that none of the other partners has ever encountered this problem. Later, it was found that it should be a system problem, because there were also byte chaos errors:
UNICODEENCODEERROR:'ascii' code can't encode...

Without mentioning this, let's look at the following mistakes: STARTF_USESHOWINDOW

Because of the company's information, so the mosaic.

Baidu for a while, found that online solutions are unreliable.

Cause of error: subprocess module was used, and the system could not find this module.

You can do a test: output subprocess under python will also report this error.

Later, it came to mind that there might be problems in the system environment and module code. At first, it replaced subprocess.py under Lib site-packages matplotlib compat, then it thought that this was a sub-module, so it replaced subprocess.py under Lib and then it ran normally.

Domestic and foreign forums have not found relevant explanations, and only after turning over the source code can we know the reason. Cmd is the command under WIN, pyc is compiled and run after compilation. Like JAVA, a compiler runs in many places at a time. If this error occurs, a small partner can find these places to replace it, or simply throw the runnable version in and overlap it. Cover it.

Let's take a look:

if mswindows:
    import threading
    import msvcrt
    import _subprocess
    class STARTUPINFO:
        dwFlags = 0
        hStdInput = None
        hStdOutput = None
        hStdError = None
        wShowWindow = 0
    class pywintypes:
        error = IOError
else:
    import select
    _has_poll = hasattr(select, 'poll')
    import fcntl
    import pickle

    # When select or poll has indicated that the file is writable,
    # we can write up to _PIPE_BUF bytes without risk of blocking.
    # POSIX defines PIPE_BUF as >= 512.
    _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)

Here we introduce the import_subprocess module, that is, subprocess.py->_subprocess.

Then locate:

if mswindows:
        #
        # Windows methods
        #

See below:

 def _execute_child(self, args, executable, preexec_fn, close_fds,
                           cwd, env, universal_newlines,
                           startupinfo, creationflags, shell, to_close,
                           p2cread, p2cwrite,
                           c2pread, c2pwrite,
                           errread, errwrite):
            """Execute program (MS Windows version)"""

            if not isinstance(args, types.StringTypes):
                args = list2cmdline(args)

            # Process startup details
            if startupinfo is None:
                startupinfo = STARTUPINFO()
            if None not in (p2cread, c2pwrite, errwrite):
                startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
                startupinfo.hStdInput = p2cread
                startupinfo.hStdOutput = c2pwrite
                startupinfo.hStdError = errwrite

            if shell:
                startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = _subprocess.SW_HIDE
                comspec = os.environ.get("COMSPEC", "cmd.exe")
                args = '{} /c "{}"'.format (comspec, args)
                if (_subprocess.GetVersion() >= 0x80000000 or
                        os.path.basename(comspec).lower() == "command.com"):
                    # Win9x, or using command.com on NT. We need to
                    # use the w9xpopen intermediate program. For more
                    # information, see KB Q150956
                    # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
                    w9xpopen = self._find_w9xpopen()
                    args = '"%s" %s' % (w9xpopen, args)
                    # Not passing CREATE_NEW_CONSOLE has been known to
                    # cause random failures on win9x.  Specifically a
                    # dialog: "Your program accessed mem currently in
                    # use at xxx" and a hopeful warning about the
                    # stability of your system.  Cost is Ctrl+C wont
                    # kill children.
                    creationflags |= _subprocess.CREATE_NEW_CONSOLE

It should be easy to see how CREATE_NEW_CONSOLE is triggered.

Let's look at the main method test entry:

"""
  KARL-Dujinyang
  QQ:309933706
"""
if __name__ == "__main__":
    if mswindows:
        _demo_windows()
    else:
        _demo_posix()

MS Windows has already been mentioned in the code at the beginning of our article. The test can be carried out here.

mswindows = (sys.platform == "win32")

_ Definition of demo_windows method:

def _demo_windows():
    #
    # Example 1: Connecting several subprocesses
    #
    print "Looking for 'PROMPT' in set output..."
    p1 = Popen("set", stdout=PIPE, shell=True)
    p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #dujinyang
    # Example 2: Simple execution of program
    #
    print "Executing calc..."
    p = Popen("calc")
    p.wait()


As you can see, this is a problem caused by OPEN - > CLOSE. If this error occurs, a small partner can find these places to replace it, or directly throw the runnable version into the cover, or find me to get the source code cover, and later if there is time I will upload a copy to CSDN.


|| Copyright Statement: This article is an original article by blogger Du Jinyang. Please indicate the origin of the article when it is reproduced.

|| Copyright Statement: This article is an original article by blogger Du Jinyang. Please indicate the origin of the article when it is reproduced.

Author: Dujinyang, Ultraman Superman

Source: CSDN

Original: https://dujinyang.blog.csdn.net/

Copyright Statement: This article is the original article of the blogger. Please attach a link to the blog article for reprinting.

Tags: Python Windows shell Attribute ascii

Posted on Thu, 05 Sep 2019 01:19:59 -0700 by Rai_de