Ansicon doesn't install from python but only from cmd

310 views Asked by At

I'm trying to install ansicon on Windows 8.1. I extracted the files and got to the level that I need to call ansicon -i. When I type this in my cmd and run python scripts that works great but when I call t from python by os.system('ansicon -i') that doesn't work and seems like it doesn't have any influence on the cmd.

Why os.system('ansicon -i') doesn't work and what alternative method can I use from within python?

1

There are 1 answers

0
icktoofay On BEST ANSWER

First off, it’s not the -i flag that really does the work. -i only tells it to add itself to AutoRun. The -p flag that -i implies is what really does the work: -p tells it to inject a DLL into the parent process, and therein lies the problem: when you use os.system, you spawn a shell, which then runs the command you give it. But then you have Python running cmd running ansicon, and ansicon will inject into cmd, and then cmd, having finished its work, will exit.

Rather than using os.system, use the subprocess module, e.g.:

subprocess.check_call(['ansicon', '-p'])

The subprocess module (unlike os.system) will execute the command directly without a shell in-between (unless you pass shell=True). Then Python will spawn ansicon, and ansicon will inject into Python, as desired.

That said, rather than having ansicon inject itself into Python, Python could probably just load the DLL itself, avoiding some hardship:

import sys
import math
import ctypes

bitness = 1 << round(math.log2(round(math.log2(sys.maxsize + 1))))
ctypes.WinDLL('ANSI{}.DLL'.format(bitness))