1,105,375 Community Members

Having troubles with CMD executed within Python

Member Avatar
Lucaci Andrew
Master Poster
746 posts since Jan 2012
Reputation Points: 128 [?]
Q&As Helped to Solve: 116 [?]
Skill Endorsements: 18 [?]
 
0
 

So, even thou I have searched throughout the forums, I couldn't get a clear answer, maybe perhaps I'm a noob @ Python.
As a beginner, I don't know much about Python, and it's frustrating to search the net and not find the actual answer.

So, I'm working on this project, and I stumbled upon this thing:
what I want to to is to open the command line(I'm working in Windows 7 ultimate) from a Python file, change the directory, of whatever is there, like, from the start cd c:\\ to the actual c: directory.
Next step comes from the user, meaning, there is an input, which requires the user to enter a path, like Users\Admin\Python27 for example.
Ok, but my problem is that I can't actually get the rite path for the cmd to access it.
To make it more clear, I'm working on the py2exe convertor, which will convert files from .py to .exe
Ok, and in this process there is a file setup.py, which holds the name of the desired .py module which the user wants to convert to .exe

What I'm trying to do is to make another module .py which will do the thing of inputing the name of the module, such as accessing that module throughout python.exe so that with 1 file access, 1 name and 1 path to actual make the convertion.

I don't know if I made myself clear. So, I need help.
Below is my code from the Start.py module, which I intend to make the things described above.

'''
Created on Feb 16, 2012

@author: sin
'''
import time
import os
import sys
n = raw_input("Name of the program: ")
p = raw_input("Name the path of your Python installer: ")
print p
time.sleep(1)
filename = 'setup1.py'
fh = open(filename, 'w')
fh.write("""from distutils.core import setup
import py2exe

setup(console=[""" + "'" + str(str(n) + '.py') + "'" + "])")
print "setup(console=[" + "'" + str(str(n) + '.py') + "'" + "])"
fh.close()
print "Your file was added"
time.sleep(2)
print "Preparing opening the command line"
time.sleep(2)
print "Accessing the command line"
time.sleep(2)
sys.path.insert(0, p)
os.system('cd c:\\')
time.sleep(1)
os.system('cd ' + str(p))
time.sleep(1)
os.system('setup1.py py2exe')

I keep getting this error:

The system cannot find the path specified.
Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

why not use os.chdir?

Member Avatar
snippsat
Veteran Poster
1,041 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 382 [?]
Skill Endorsements: 10 [?]
 
1
 

I'm working on the py2exe convertor, which will convert files from .py to .exe

It seems like you are making this to diffcult and you are missing stuff like setup option.
Look at this,will convert py file to exe.

from distutils.core import setup
import py2exe
import sys

def py2_exe(file_in=None):
    if len(sys.argv) == 1:
        sys.argv.append('py2exe')

    setup(options = {'py2exe': {'compressed': 1, 'optimize': 2, 'ascii': 1, 'bundle_files': 3}},
           zipfile = None,

           ## Can use console or window
           ## Filpath to '....py' run this script in same folder as file_in
          console = [{'script': file_in}])

if __name__ == '__main__':
    #Use raw string then you dont need \\ or /
    file_in = r'c:\test\singel_digits.py'
    py2_exe(file_in)

There is also Gui2exe you can look at.

Member Avatar
Lucaci Andrew
Master Poster
746 posts since Jan 2012
Reputation Points: 128 [?]
Q&As Helped to Solve: 116 [?]
Skill Endorsements: 18 [?]
 
0
 

Thank you for that, but I made some improvements to this code:

from distutils.core import setup
import py2exe
import sys
import os
import time

"""
Destination of the current setup file
"""
print "Destination of the current " + str(os.path.basename(sys.argv[0])) + " file."
print 'Raw path - sys.argv[0] =', sys.argv[0]    
pathname = os.path.dirname(sys.argv[0])                 
print 'Current path =', pathname
print 'Full path =', os.path.abspath(pathname)

#Do not modify from further on!!!:
class _extraOptions:
    def __init__(self):
#The files marked as comments are the initialized objects from py2exe which should not be modified, and if so, with no effect:D 
        self.xref = 0
        self.compressed = 0
#        self.unbuffered = 0
        self.optimize = 0
        self.includes = None
        self.excludes = None
        self.ignores = None
        self.packages = None
#        self.dist_dir = None
        self.dll_excludes = None
#        self.typelibs = None
        self.bundle_files = 3
        self.skip_archive = 0
        self.ascii = 0
        self.custom_boot_script = None
        
    def extra(self):
        print """
            Extra .exe option at the compress files:
                    Optimize:
         Optimization level: -O1 for \"python -O\
                                                              -O2 for \"python -OO\
                        
                    Excludes:
         Comma-separated list of modules to exclude
                    Dll-Excludes:
         Comma-separated list of DLLs to exclude
                    Ignores:
         Comma-separated list of modules to ignore if they are not found
                    Includes:
         Comma-separated list of modules to include
                    Packages:
         Comma-separated list of packages to include
                    Compress:
         Create a compressed zipfile
                    X-ref:
         Create and show a module cross reference
                    Bundle-files:
         Bundle dlls in the zipfile or the exe. 
         Valid levels are 1, 2, or 3 (default)
                    Skip-archive:
         Do not place Python bytecode files in an archive, put them directly in the file system
                    Ascii:
         Do not automatically include encodings and codecs
                    Custom Bot script:
         Python file that will be run when setting up the runtime environment
         """
    def init(self):
        print """ Initial values extracted from the Built module of py2exe:
                xref =0
                compressed = 0
                unbuffered = 0
                optimize = 0
                includes = None
                excludes = None
                ignores = None
                packages = None
                dist_dir = None
                dll_excludes = None
                typelibs = None
                bundle_files = 3
                skip_archive = 0
                ascii = 0
                custom_boot_script = None
        """
    def commands(self):
        print """
        1. Optimize
        2. Excludes
        3. Dll-Exclides
        4. Ignores
        5. Includes
        6. Packages
        7. Compress
        8. X-Ref
        9. Bundle-files
        10. Skip-archive
        11. Ascii
        12. Custom bot script
        
        Also:
        Type exit, back or break to break and return.
        """
        while True:
            cmd = str.lower(raw_input("Insert command: "))
            if cmd == '1' or cmd == '1.':
                opt = int(raw_input("New optimization (int): "))
                self.optimize = opt

            elif cmd == '2' or cmd == '2.':
                exclude = raw_input("Modules excluded (separated by comma, and with .pw ENDING!!: \n")
                _excludeData = exclude.split(',')
                self.excludes = _excludeData

            elif cmd == '3' or cmd == '3.':
                dllsExcld = raw_input("Dlls to be ecluded (separated by comma): \n")
                _dllsExcldData = dllsExcld.split(',')
                self.dll_excludes = _dllsExcldData
                
            elif cmd == '4' or cmd == '4.':
                ign = raw_input("Modules ignored (separated by comma, and with .py ENDING!!): \n")
                _ignData = ign.split(',')
                self.ignores = _ignData
        
            elif cmd == '5' or cmd == '5.':
                incld = raw_input("Modules included (separated by comma, and with .py ENDING!!): \n")
                _incldData = incld.split(',')
                self.includes = _incldData
            
            elif cmd == '6' or cmd == '6.':
                packages = raw_input("Packages to be included (separated by comma: \n")
                _packagesData = packages.split(',')
                self.packages = _packagesData
            
            elif cmd == '7' or cmd == '7.':
                comp = int(raw_input("New compression (int): "))
                self.compressed = comp
            
            elif cmd == '8' or cmd == '8.':
                xref = int(raw_input("New x-ref (int): "))
                self.xref = xref
            
            elif cmd == '9' or cmd == '9.':
                bundl = int(raw_input("New bundle (int - 1-3): "))
                self.bundle_files = bundl
            
            elif cmd == '10' or cmd == '10.':
                skip = int(raw_input("New skip-file (int): "))
                self.skip_archive = skip
            
            elif cmd == '11' or cmd == '11.':
                ascii = int(raw_input("New Ascii (int): "))
                self.ascii = ascii
            
            elif cmd == '12' or cmd == '12.':
                custombot = raw_input("Name of the file which will be the custom bot script (without .py termination): \n") + '.py'
                self.custom_boot_script = custombot
            
            elif cmd == 'back' or cmd == 'exit' or cmd == 'break':
                print "Returning to the other menu."
                time.sleep(2)
                break
                            
            #Sort of hidden commands, for verification at testing and rundowns. If so, type
            #these commands to show the actual value of the parameters
            elif cmd == 'print opt': print self.optimize
            elif cmd == 'print exclude': print self.excludes
            elif cmd == 'print dlls': print self.dll_excludes
            elif cmd == 'print ign': print self.ignores
            elif cmd == 'print include': print self.includes
            elif cmd == 'print packages': print self.packages
            elif cmd == 'print compress': print self.compressed
            elif cmd == 'print xref': print self.xref
            elif cmd == 'print bundle': print self.bundle_files
            elif cmd == 'print skip': print self.skip_archive
            elif cmd == 'print ascii': print self.ascii
            elif cmd == 'print custom': print self.custom_boot_script
            
            else: print "Invalid command. \n"
            
    def print_menu(self):
        print"""            Menu of the custom options:
    1. Displays the informations about each function
    2. Displays the initial value of the parameters, taken from the py2exe 
module, build_exe.py
    3. The actual command-menu.
    
    Additional commands:
        Type: exit, back or break to exit this menu.
        Type: menu to view again the options.
        Type: help to view the help menu.
        """
        
    def print_help_menu(self):
        print """            Help menu
    For additional help visit the Internet or other sources.
    1. General information about these options.
    2. How to access the menu or the submenus.
    3. Return to Main menu.
    
    Additional commands:
    Type 'show' to view again this menu.
    """
    
    def help(self):
        while True:
            _help_cmd = str.lower(raw_input("Insert command: "))
            if _help_cmd == '1' or _help_cmd == '1.':
                print """    These options are meant for advanced 
programmers with more than simple needs. It is required to access the 
information only for the needs, not to 'see what happens'.
Note that if you change some settings, some of the features won't work, 
or (for sure) you will chars the program. All that you do in this part
is strictly your business, but be aware of the consequences.
                Happy coding, love from s|n.
                        """
            elif _help_cmd == '2' or _help_cmd == '2.':
                print """    For accessing the menus or the submenus in which you are required
to enter some numbers, just use this notation:
        If you are asked for a command (as you have seen before) "Insert 
command: " you are required to enter only the number of the item from the 
menu, for example 1 and 1. will point to the command 1 from the menu.
        If you want to exit, or to see other menus, there are specific 
commands for that, and they are noted under the "Additional commands" 
info, for example Type exit, back or break to exit. In that case you are 
required to enter either lowercase or uppercase or whatever, it's case 
insensitive, the exact text, meaning exit or break or back.
    
            That's all. Happy coding, love from s|n.
                        """
            elif _help_cmd == '3' or _help_cmd == '3.' or _help_cmd == 'exit' or _help_cmd == 'back' or _help_cmd == 'break':
                print "Returning to the other menu."
                time.sleep(2)
                break
            
            elif _help_cmd == 'show':
                self.print_help_menu()
            else: 
                print "Invalid command."
        
    def run(self):
        self.print_menu()
        while True:
            _cmd = str.lower(raw_input("Insert command: "))
            if _cmd == '1' or _cmd == '1.':
                self.extra()
            elif _cmd == '2' or _cmd == '2.':
                self.init()
            elif _cmd == '3' or _cmd == '3.':
                self.commands()
            elif _cmd == 'exit' or _cmd == 'back' or _cmd == 'break':
                print "Returning to the actual program."
                time.sleep(2)
                print "Make sure you made the rite modifications"
                time.sleep(2)
                print 'BB:D'
                time.sleep(1)
                break
            elif _cmd == 'menu':
                self.print_menu()
            elif _cmd == 'help':
                self.print_help_menu()
                self.help()
            else:
                print "Invalid command."
         
e = _extraOptions()       
print "You need py2exe module in order for this to work."
time.sleep(1)
print "Checking file integrity..."
time.sleep(2)
print "Done injecting..."
time.sleep(1)
i = -1
while i != 'ok': 
    errors = []
    fl = raw_input("File: ")
    if fl == 'exit':
        print "Initialized sys.exit() command. BB!"
        time.sleep(2)
        sys.exit()
    _rawpath = os.path.isfile(pathname + '\\' + fl + '.py')
    if _rawpath == True:
        print "Do you want to enter the Extra-option menu? (for advanced Python users)"
        print "If you are undecided just type 'n' and continue with the default values (Best)."
        p = str.lower(raw_input("Enter?: y/n \n"))
        if p == "y" or p == 'yes':
            e.run()
        d = "Exe\\" + raw_input("Output folder: (example:" + str(pathname) + '\\Exe\\My \n Output Folder' + "): \n")
        if d == 'Exe\\' + 'exit':
            print "Initialized sys.exit() command. BB!"
            time.sleep(2)
            sys.exit()
    else: 
        er = "There is no such file located at the address: \n" + str(pathname)
        errors.append(er)
        print errors[0]
    if len(errors) == 0:
        i = 'ok'
        
"""
Initialization of the values with their initial state
"""
xref = e.xref
compress = e.compressed
optimized = e.optimize
include = e.includes
exclude = e.excludes
ignore = e.ignores
package = e.packages
dll = e.dll_excludes
bundle = e.bundle_files
skip = e.skip_archive
ascii = e.ascii
custom = e.custom_boot_script

def exe(__init_file__=None):
    if len(sys.argv) == 1:
        sys.argv.append('py2exe')

    #Options for the exe file.
    setup(options={'py2exe': {'dist_dir':d,
                              'compressed': compress,
                              'optimize': optimized,
                              'ascii': ascii,
                              'bundle_files': bundle,
                              'includes':include,
                              'excludes':exclude,
                              'ignores':ignore,
                              'packages':package,
                              'dll_excludes':dll,
                              'skip_archive':skip,
                              'custom_boot_script':custom
                              }},
           zipfile=None,
          console=[{'script': __init_file__}])

if __name__ == '__main__':
    __init_file__ = pathname + '\\' + fl + '.py'
    exe(__init_file__)
print "\n\nYour files were added to the path: " "\n", pathname + "\\" + d
print "Done converting. Extra coding by Lucaci Andrei (AKA s|n) February 17, 2012. "
print "Keep coding..."
time.sleep(10)

You must have the .py file in the same directory as this file, and the py2exe module installed.
Hope you like it.

Question Answered as of 2 Years Ago by snippsat and pyTony
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: