Ejemplo n.º 1
0
    def getTempFile(self, suffix=''):
        '''
        gets a temporary file with a suffix that will work for a bit.
        note that the file is closed after finding, so some older versions
        of python/OSes, etc. will immediately delete the file.
        '''
        # get the root dir, which may be the user-specified dir
        rootDir = self.getRootTempDir()
        if len(suffix) > 0 and not suffix.startswith('.'):
            suffix = '.' + suffix


        if common.getPlatform() != 'win':
            fileDescriptor, filePath = tempfile.mkstemp(
                dir=rootDir, suffix=suffix)
            if isinstance(fileDescriptor, int):
                # on MacOS, fd returns an int, like 3, when this is called
                # in some context (specifically, programmatically in a
                # TestExternal class. the filePath is still valid and works
                pass
            else:
                fileDescriptor.close()
        else:  # win
            tf = tempfile.NamedTemporaryFile(dir=rootDir, suffix=suffix)
            filePath = tf.name
            tf.close()
        #self.printDebug([_MOD, 'temporary file:', filePath])
        return filePath
Ejemplo n.º 2
0
    def launch(self, filePath, fmt=None, options='', app=None, key=None):
        '''
        Opens the appropriate viewer for the file generated by .write()
        '''
        if fmt is None and self.registerShowFormats:
            fmt = self.registerShowFormats[0]    
        if app is None:
            if key is not None:
                app = environLocal._ref[key]
            elif self.launchKey is not None:
                app = environLocal._ref[self.launchKey]
            else:
                app = environLocal.formatToApp(fmt)

        platform = common.getPlatform()
        if app is None:
            if platform == 'win':
                # no need to specify application here:
                # windows starts the program based on the file extension
                cmd = 'start %s' % (filePath)
            elif platform == 'darwin':
                cmd = 'open %s %s' % (options, filePath)
            else:
                raise SubConverterException(
                    "Cannot find a valid application path for format {}. "
                    "Specify this in your Environment by calling "
                    "environment.set({!r}, 'pathToApplication')".format(
                        self.registerFormats[0], self.launchKey))
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (app, options, filePath)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (app, options, filePath)
        elif platform == 'nix':
            cmd = '%s %s %s' % (app, options, filePath)
        os.system(cmd)
Ejemplo n.º 3
0
    def loadDefaults(self):
        '''Load defaults. All keys are derived from these defaults.
        '''
        self.ref['directoryScratch'] = None # path to a directory for temporary files
        self.ref['lilypondPath'] = None # path to lilypond
        self.ref['lilypondVersion'] = None # version of lilypond
        self.ref['lilypondFormat'] = 'pdf' 
        self.ref['lilypondBackend'] = 'ps' 
        self.ref['musicxmlPath'] = None # path to a MusicXML reader: default, will find "Finale Reader"
        self.ref['midiPath'] = None # path to a midi reader
        self.ref['graphicsPath'] = None # path to a graphics viewer
        self.ref['showFormat'] = 'musicxml' 
        self.ref['writeFormat'] = 'musicxml' 
        self.ref['autoDownload'] = 'ask' 
        self.ref['debug'] = 0

        platform = common.getPlatform()

        if platform == 'win':
            for name, value in [
                ('lilypondPath', 'lilypond'),
                ]:
                self.__setitem__(name, value) # use for key checking
        elif platform == 'nix':
            for name, value in [('lilypondPath', 'lilypond')]:
                self.__setitem__(name, value) # use for key checking
        elif platform ==  'darwin':
            for name, value in [
                ('lilypondPath', '/Applications/Lilypond.app/Contents/Resources/bin/lilypond'),
                ('musicxmlPath', '/Applications/Finale Reader/Finale Reader.app'),
                ('graphicsPath', '/Applications/Preview.app'),
                ]:
                self.__setitem__(name, value) # use for key checking
Ejemplo n.º 4
0
    def getTempFile(self, suffix=''):
        '''
        gets a temporary file with a suffix that will work for a bit.
        note that the file is closed after finding, so some older versions
        of python/OSes, etc. will immediately delete the file.
        '''
        # get the root dir, which may be the user-specified dir
        rootDir = self.getRootTempDir()

        if common.getPlatform() != 'win':
            fd, fp = tempfile.mkstemp(dir=rootDir, suffix=suffix)
            if isinstance(fd, int):
                # on MacOS, fd returns an int, like 3, when this is called
                # in some context (specifically, programmatically in a
                # TestExternal class. the fp is still valid and works
                pass
            else:
                fd.close()
        else:  # win
            if sys.hexversion < 0x02030000:
                raise EnvironmentException(
                    "Need at least Version 2.3 on Windows to create temporary files!"
                )
            else:
                tf = tempfile.NamedTemporaryFile(dir=rootDir, suffix=suffix)
                fp = tf.name
                tf.close()
        #self.printDebug([_MOD, 'temporary file:', fp])
        return fp
Ejemplo n.º 5
0
    def launch(self, filePath, fmt=None, options='', app=None, key=None):
        if fmt is None and len(self.registerShowFormats) > 0:
            fmt = self.registerShowFormats[0]
        if app is None:
            if key is not None:
                app = environLocal._ref[key]
            elif self.launchKey is not None:
                app = environLocal._ref[self.launchKey]
            else:
                app = environLocal.formatToApp(fmt)

        platform = common.getPlatform()
        if app is None:
            if platform == 'win':
                # no need to specify application here:
                # windows starts the program based on the file extension
                cmd = 'start %s' % (filePath)
            elif platform == 'darwin':
                cmd = 'open %s %s' % (options, filePath)
            else:
                raise SubConverterException(
                    "Cannot find a valid application path for format {}. "
                    "Specify this in your Environment by calling "
                    "environment.set({!r}, 'pathToApplication')".format(
                        self.registerFormats[0], self.launchKey))
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (app, options, filePath)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (app, options, filePath)
        elif platform == 'nix':
            cmd = '%s %s %s' % (app, options, filePath)
        os.system(cmd)
Ejemplo n.º 6
0
 def getSettingsPath(self):
     platform = common.getPlatform()
     if platform == 'win':
         # try to use defined app data directory for preference file
         # this is not available on all windows versions
         if 'APPDATA' in os.environ:
             directory = os.environ['APPDATA']
         elif ('USERPROFILE' in os.environ and
             os.path.exists(os.path.join(
                 os.environ['USERPROFILE'], 'Application Data'))):
             directory = os.path.join(
                 os.environ['USERPROFILE'],
                 'Application Data',
                 )
         else:  # use home directory
             directory = os.path.expanduser('~')
         return os.path.join(directory, 'music21-settings.xml')
     elif platform in ['nix', 'darwin']:
         # alt : os.path.expanduser('~')
         # might not exist if running as nobody in a webserver...
         if 'HOME' in os.environ:
             directory = os.environ['HOME']
         else:
             directory = '/tmp/'
         return os.path.join(directory, '.music21rc')
Ejemplo n.º 7
0
    def launchGregorio(self, fp = None):
        '''
        converts a .gabc file to LaTeX using the
        gregorio converter.  Returns the filename with .tex substituted for .gabc
        
        >>> bsc = alpha.chant.BaseScoreConverter()
        >>> #_DOCS_SHOW newFp = bsc.launchGregorio('~cuthbert/Library/Gregorio/examples/Populas.gabc')
        >>> #_DOCS_SHOW bsc.gregorioCommand
        >>> 'open -a"/usr/local/bin/gregorio"  ~cuthbert/Library/Gregorio/examples/Populas.gabc' #_DOCS_HIDE
        'open -a"/usr/local/bin/gregorio"  ~cuthbert/Library/Gregorio/examples/Populas.gabc'
        
        
        More often, you'll want to write a textfile from writeFile:
        
        '''
        platform = common.getPlatform()
        fpApp = self.gregorioConverter
        options = self.gregorioOptions

        if platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin':
            cmd = '%s %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)        
        self.gregorioCommand = cmd
        os.system(cmd)
        newfp = re.sub(r'\.gabc', '.tex', fp)
        return newfp
Ejemplo n.º 8
0
    def launchGregorio(self, fp = None):
        '''
        converts a .gabc file to LaTeX using the
        gregorio converter.  Returns the filename with .tex substituted for .gabc
        
        
        >>> bsc = chant.BaseScoreConverter()
        >>> #_DOCS_SHOW newFp = bsc.launchGregorio('~cuthbert/Library/Gregorio/examples/Populas.gabc')
        >>> #_DOCS_SHOW bsc.gregorioCommand
        >>> u'open -a"/usr/local/bin/gregorio"  ~cuthbert/Library/Gregorio/examples/Populas.gabc' #_DOCS_HIDE
        u'open -a"/usr/local/bin/gregorio"  ~cuthbert/Library/Gregorio/examples/Populas.gabc'
        
        
        More often, you'll want to write a textfile from writeFile:
        
        
        '''

        
        platform = common.getPlatform()
        fpApp = self.gregorioConverter
        options = self.gregorioOptions

        if platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin':
            cmd = '%s %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)        
        self.gregorioCommand = cmd
        os.system(cmd)
        newfp = re.sub('\.gabc', '.tex', fp)
        return newfp
Ejemplo n.º 9
0
    def getTempFile(self, suffix=''):
        '''Return a file path to a temporary file with the specified suffix
        '''
        # get the root dir, which may be the user-specified dir
        rootDir = self.getRootTempDir()

        if common.getPlatform() != 'win':
            fd, fp = tempfile.mkstemp(dir=rootDir, suffix=suffix)
            if isinstance(fd, int):
                # on MacOS, fd returns an int, like 3, when this is called
                # in some context (specifically, programmatically in a 
                # TestExternal class. the fp is still valid and works
                pass
            else:
                fd.close() 
        else: # win
            if sys.hexversion < 0x02030000:
                raise EnvironmentException("Need at least Version 2.3 on Windows to create temporary files!")
            else:
                tf = tempfile.NamedTemporaryFile(dir=rootDir, suffix=suffix)
                fp = tf.name
                tf.close()

        self.printDebug([_MOD, 'temporary file:', fp])
        return fp
Ejemplo n.º 10
0
 def getSettingsPath(self):
     platform = common.getPlatform()
     if platform == 'win':
         # try to use defined app data directory for preference file
         # this is not available on all windows versions
         if 'APPDATA' in os.environ:
             directory = os.environ['APPDATA']
         elif ('USERPROFILE' in os.environ and os.path.exists(
                 os.path.join(os.environ['USERPROFILE'],
                              'Application Data'))):
             directory = os.path.join(
                 os.environ['USERPROFILE'],
                 'Application Data',
             )
         else:  # use home directory
             directory = os.path.expanduser('~')
         return os.path.join(directory, 'music21-settings.xml')
     elif platform in ['nix', 'darwin']:
         # alt : os.path.expanduser('~')
         # might not exist if running as nobody in a webserver...
         if 'HOME' in os.environ:
             directory = os.environ['HOME']
         else:
             directory = '/tmp/'
         return os.path.join(directory, '.music21rc')
Ejemplo n.º 11
0
    def main(self, format):
        '''Create the documentation. 
        '''
        if format not in FORMATS:
            raise Exception, 'bad format'

        self.writeModuleReference()    
        self.writeGeneratedChapters()    
        self.writeContents()    

        if format == 'html':
            dirOut = self.dirBuildHtml
            pathLaunch = os.path.join(self.dirBuildHtml, 'contents.html')
        elif format == 'latex':
            dirOut = self.dirBuildLatex
            #pathLaunch = os.path.join(dirBuildHtml, 'contents.html')
        elif format == 'pdf':
            dirOut = self.dirBuildPdf
        else:
            raise Exception('undefined format %s' % format)

        if common.getPlatform() in ['darwin', 'nix', 'win']:
            # -b selects the builder
            import sphinx
            sphinxList = ['sphinx', '-E', '-b', format, '-d', self.dirBuildDoctrees,
                         self.dirRst, dirOut] 
            sphinx.main(sphinxList)
    
        if format == 'html':
            webbrowser.open(pathLaunch)
Ejemplo n.º 12
0
    def getTempFile(self, suffix=''):
        '''
        gets a temporary file with a suffix that will work for a bit.
        note that the file is closed after finding, so some older versions
        of python/OSes, etc. will immediately delete the file.
        '''
        # get the root dir, which may be the user-specified dir
        rootDir = self.getRootTempDir()
        if len(suffix) > 0 and not suffix.startswith('.'):
            suffix = '.' + suffix

        if common.getPlatform() != 'win':
            fileDescriptor, filePath = tempfile.mkstemp(dir=rootDir,
                                                        suffix=suffix)
            if isinstance(fileDescriptor, int):
                # on MacOS, fd returns an int, like 3, when this is called
                # in some context (specifically, programmatically in a
                # TestExternal class. the filePath is still valid and works
                pass
            else:
                fileDescriptor.close()
        else:  # win
            tf = tempfile.NamedTemporaryFile(dir=rootDir, suffix=suffix)
            filePath = tf.name
            tf.close()
        #self.printDebug([_MOD, 'temporary file:', filePath])
        return filePath
Ejemplo n.º 13
0
    def launchGregorio(self, fp=None):
        """
        converts a .gabc file to LaTeX using the
        gregorio converter.  Returns the filename with .tex substituted for .gabc
        
        >>> bsc = alpha.chant.BaseScoreConverter()
        >>> fn = '~cuthbert/Library/Gregorio/examples/Populas.gabc'
        >>> #_DOCS_SHOW newFp = bsc.launchGregorio(fn)
        >>> #_DOCS_SHOW bsc.gregorioCommand
        >>> 'open -a"/usr/local/bin/gregorio" ' + fn #_DOCS_HIDE
        'open -a"/usr/local/bin/gregorio"  ~cuthbert/Library/Gregorio/examples/Populas.gabc'
        
        
        More often, you'll want to write a textfile from writeFile:
        
        """
        platform = common.getPlatform()
        fpApp = self.gregorioConverter
        options = self.gregorioOptions

        if platform == "win":  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == "darwin":
            cmd = "%s %s %s" % (fpApp, options, fp)
        elif platform == "nix":
            cmd = "%s %s %s" % (fpApp, options, fp)
        self.gregorioCommand = cmd
        os.system(cmd)
        newfp = re.sub(r"\.gabc", ".tex", fp)
        return newfp
Ejemplo n.º 14
0
def main(fnAccept=None):
    '''
    `fnAccept` is a list of one or more files to test.
    '''

    mg = test.ModuleGather()

    # only accept a few file names for now
    if fnAccept in [None, []]:
        fnAccept = ['note.py']

        #fnAccept = ['stream.py', 'note.py', 'chord.py']

    disable = ['C0301', 'C0302', 'C0103', 'C0324', 'W0621', 'W0511', 
               'W0404', 'R0201', 'R0904', 'E1101', 'R0914', 'R0903',
               'R0911', 'R0902', ]

    cmd = ['pylint -f colorized']
    for id in disable:
        cmd.append('--disable=%s' % id)

    # add entire package
    for fp in mg.modulePaths:
        dir, fn = os.path.split(fp)
        fnNoExt = fn.replace('.py', '')
        if fn in fnAccept or fnNoExt in fnAccept:
            cmdFile = cmd + [fp]
            print(' '.join(cmdFile))
            if common.getPlatform() != 'win':
                os.system(' '.join(cmdFile))
Ejemplo n.º 15
0
    def launch(self, fmt, fp, options='', app=None):
        # see common.fileExtensions for format names
        m21Format, unused_ext = common.findFormat(fmt)
        if m21Format == 'lilypond':
            environmentKey = 'lilypondPath'
        elif m21Format in ['png', 'jpeg']:
            environmentKey = 'graphicsPath'
        elif m21Format in ['svg']:
            environmentKey = 'vectorPath'
        elif m21Format in ['pdf']:
            environmentKey = 'pdfPath'
        elif m21Format == 'musicxml':
            environmentKey = 'musicxmlPath'
        elif m21Format == 'midi':
            environmentKey = 'midiPath'
        elif m21Format == 'vexflow':
            try:
                import webbrowser
                if fp.find('\\') != -1:
                    pass
                else:
                    if fp.startswith('/'):
                        fp = 'file://' + fp

                webbrowser.open(fp)
                return
            except:
                print "Cannot open webbrowser, sorry.  go to file://%s" % fp
        else:
            environmentKey = None
            fpApp = None

        if environmentKey is not None:
            fpApp = self._ref[environmentKey]

        # substitute app provided via argument
        if app is not None:
            fpApp = app

        platform = common.getPlatform()
        if fpApp is None and platform not in ['win', 'darwin']:
            raise EnvironmentException(
                "Cannot find a valid application path for format %s. Specify this in your Environment by calling environment.set(%r, 'pathToApplication')"
                % (m21Format, environmentKey))

        if platform == 'win' and fpApp is None:
            # no need to specify application here: windows starts the program based on the file extension
            cmd = 'start %s' % (fp)
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin' and fpApp is None:
            cmd = 'open %s %s' % (options, fp)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)
        os.system(cmd)
Ejemplo n.º 16
0
    def launch(self, fmt, fp, options='', app=None):
        # see common.fileExtensions for format names 
        format, ext = common.findFormat(fmt)
        if format == 'lilypond':
            environmentKey = 'lilypondPath'
        elif format in ['png', 'jpeg']:
            environmentKey = 'graphicsPath'
        elif format in ['svg']:
            environmentKey = 'vectorPath'
        elif format in ['pdf']:
            environmentKey = 'pdfPath'
        elif format == 'musicxml':
            environmentKey = 'musicxmlPath'
        elif format == 'midi':
            environmentKey = 'midiPath'
        elif format == 'vexflow':
            try:
                import webbrowser
                if fp.find('\\') != -1:
                    pass
                else:
                    if fp.startswith('/'):
                        fp = 'file://' + fp
                
                webbrowser.open(fp)
                return
            except:
                print "Cannot open webbrowser, sorry.  go to file://%s" % fp
        else:
            environmentKey = None
            fpApp = None

        if environmentKey is not None:
            fpApp = self._ref[environmentKey]

        # substitute app provided via argument
        if app is not None:
            fpApp = app 

        platform = common.getPlatform()
        if fpApp is None and platform not in ['win', 'darwin']:
            raise EnvironmentException("Cannot find a valid application path for format %s. Specify this in your Environment by calling environment.set(%r, 'pathToApplication')" % (format, environmentKey))
        
        if platform == 'win' and fpApp is None:
            # no need to specify application here: windows starts the program based on the file extension
            cmd = 'start %s' % (fp)
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin' and fpApp is None:
            cmd = 'open %s %s' % (options, fp)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)
        os.system(cmd)
Ejemplo n.º 17
0
    def _loadDefaults(self, forcePlatform=None):
        '''Load defaults. All keys are derived from these defaults.
        '''
        self._ref[
            'directoryScratch'] = None  # path to a directory for temporary files
        self._ref['lilypondPath'] = None  # path to lilypond
        self._ref['lilypondVersion'] = None  # version of lilypond
        self._ref['lilypondFormat'] = 'pdf'
        self._ref['lilypondBackend'] = 'ps'
        # path to a MusicXML reader: default, will find "Finale Notepad"
        self._ref['musicxmlPath'] = None
        self._ref['midiPath'] = None  # path to a midi reader
        self._ref['graphicsPath'] = None  # path to a graphics viewer
        self._ref['vectorPath'] = None  # path to a vector graphics viewer
        self._ref['pdfPath'] = None  # path to a pdf viewer

        # path to MuseScore (if not the musicxmlPath...) for direct creation of PNG from MusicXML
        self._ref['musescoreDirectPNGPath'] = None
        self._ref['showFormat'] = 'musicxml'
        self._ref['writeFormat'] = 'musicxml'
        self._ref['autoDownload'] = 'ask'
        self._ref['debug'] = 0
        # printing of missing import warnings
        self._ref['warnings'] = 1  # default/non-zero is on

        # store a list of strings
        self._ref['localCorpusSettings'] = []

        if forcePlatform is None:
            platform = common.getPlatform()
        else:
            platform = forcePlatform

        if platform == 'win':
            for name, value in [
                ('lilypondPath', 'lilypond'),
            ]:
                self.__setitem__(name, value)  # use for key checking
        elif platform == 'nix':
            for name, value in [('lilypondPath', 'lilypond')]:
                self.__setitem__(name, value)  # use for key checking
        elif platform == 'darwin':
            for name, value in [
                ('lilypondPath',
                 '/Applications/Lilypond.app/Contents/Resources/bin/lilypond'),
                ('musicxmlPath', '/Applications/Finale Notepad 2012.app'),
                ('graphicsPath', '/Applications/Preview.app'),
                ('vectorPath', '/Applications/Preview.app'),
                ('pdfPath', '/Applications/Preview.app'),
                ('midiPath', '/Applications/QuickTime Player.app'),
                ('musescoreDirectPNGPath',
                 '/Applications/MuseScore.app/Contents/MacOS/mscore'),
            ]:
                self.__setitem__(name, value)  # use for key checking
Ejemplo n.º 18
0
    def _loadDefaults(self, forcePlatform=None):
        '''Load defaults. All keys are derived from these defaults.
        '''
        self._ref['directoryScratch'] = None # path to a directory for temporary files
        self._ref['lilypondPath'] = None # path to lilypond
        self._ref['lilypondVersion'] = None # version of lilypond
        self._ref['lilypondFormat'] = 'pdf' 
        self._ref['lilypondBackend'] = 'ps' 
        # path to a MusicXML reader: default, will find "Finale Notepad"
        self._ref['musicxmlPath'] = None 
        self._ref['midiPath'] = None # path to a midi reader
        self._ref['graphicsPath'] = None # path to a graphics viewer
        self._ref['vectorPath'] = None # path to a vector graphics viewer
        self._ref['pdfPath'] = None # path to a pdf viewer

        # path to MuseScore (if not the musicxmlPath...) for direct creation of PNG from MusicXML
        self._ref['musescoreDirectPNGPath'] = None
        self._ref['showFormat'] = 'musicxml' 
        self._ref['writeFormat'] = 'musicxml' 
        self._ref['autoDownload'] = 'ask' 
        self._ref['debug'] = 0
        # printing of missing import warnings
        self._ref['warnings'] = 1 # default/non-zero is on

        # store a list of strings
        self._ref['localCorpusSettings'] = [] 

        if forcePlatform is None:
            platform = common.getPlatform()
        else:
            platform = forcePlatform

        if platform == 'win':
            for name, value in [
                ('lilypondPath', 'lilypond'),
                ]:
                self.__setitem__(name, value) # use for key checking
        elif platform == 'nix':
            for name, value in [('lilypondPath', 'lilypond')]:
                self.__setitem__(name, value) # use for key checking
        elif platform ==  'darwin':
            for name, value in [
            ('lilypondPath', '/Applications/Lilypond.app/Contents/Resources/bin/lilypond'),
            ('musicxmlPath', '/Applications/Finale Notepad 2012.app'),
            ('graphicsPath', '/Applications/Preview.app'),
            ('vectorPath', '/Applications/Preview.app'),
            ('pdfPath', '/Applications/Preview.app'),
            ('midiPath', '/Applications/QuickTime Player.app'),
            ('musescoreDirectPNGPath', '/Applications/MuseScore.app/Contents/MacOS/mscore'),
                ]:
                self.__setitem__(name, value) # use for key checking
Ejemplo n.º 19
0
    def launch(self, fmt, fp, options='', app=None):
        '''
        Opens a file with an either default or user-specified applications.
        
        OMIT_FROM_DOCS

        Optionally, can add additional command to erase files, if necessary 
        Erase could be called from os or command-line arguments after opening
        the file and then a short time delay.

        TODO: Move showImageDirectfrom lilyString.py ; add MIDI
        TODO: Switch to module subprocess to prevent hanging.
        '''
        # see common.fileExtensions for format names 
        format, ext = common.findFormat(fmt)
        if format == 'lilypond':
            fpApp = self.ref['lilypondPath']
        elif format in ['png', 'jpeg']:
            fpApp = self.ref['graphicsPath']   
        elif format in ['pdf']:
            fpApp = self.ref['pdfPath']   
        elif format == 'musicxml':
            fpApp = self.ref['musicxmlPath']   
        elif format == 'midi':
            fpApp = self.ref['midiPath']   
        else:
            fpApp = None

        # substitute provided app
        if app != None:
            fpApp = app 

        platform = common.getPlatform()
        if fpApp is None and platform != 'win':
            raise EnvironmentException("Cannot find an application for format %s, specify this in your environment" % fmt)
        
        if platform == 'win' and fpApp is None:
            # no need to specify application here: windows starts the program based on the file extension
            cmd = 'start %s' % (fp)
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)
        print cmd
        os.system(cmd)
Ejemplo n.º 20
0
    def launch(self, filePath, fmt=None,
               options='', app=None, launchKey=None): # pragma: no cover
        '''
        Opens the appropriate viewer for the file generated by .write()

        app is the path to an application to launch.  Specify it and/or a launchKey
        launchKey is the specific key in .music21rc (such as graphicsPath), etc.
        to search for the application.  If it's not specified then there might be
        a default one for the converter in self.launchKey.  If it can't find it
        there then environLocal.formatToApp(fmt) will be used.
        '''
        if fmt is None and self.registerShowFormats:
            fmt = self.registerShowFormats[0]
        if app is None:
            if launchKey is not None:
                app = environLocal[launchKey]
            elif self.launchKey is not None:
                launchKey = self.launchKey
                app = environLocal[launchKey]
            else:
                launchKey = environLocal.formatToKey(fmt)
                app = environLocal.formatToApp(fmt)

        platform = common.getPlatform()
        if app is None:
            if platform == 'win':
                # no need to specify application here:
                # windows starts the program based on the file extension
                cmd = 'start %s' % (filePath)
            elif platform == 'darwin':
                cmd = 'open %s %s' % (options, filePath)
            else:
                raise SubConverterException(
                    "Cannot find a valid application path for format {}. "
                    "Specify this in your Environment by calling "
                    "environment.set({!r}, '/path/to/application')".format(
                        fmt, launchKey))
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (app, options, filePath)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (app, options, filePath)
        elif platform == 'nix':
            cmd = '%s %s %s' % (app, options, filePath)
        os.system(cmd)
Ejemplo n.º 21
0
    def launch(self, filePath, fmt=None, options='', app=None, launchKey=None):
        '''
        Opens the appropriate viewer for the file generated by .write()

        app is the path to an application to launch.  Specify it and/or a launchKey
        launchKey is the specific key in .music21rc (such as graphicsPath), etc.
        to search for the application.  If it's not specified then there might be
        a default one for the converter in self.launchKey.  If it can't find it
        there then environLocal.formatToApp(fmt) will be used.
        '''
        if fmt is None and self.registerShowFormats:
            fmt = self.registerShowFormats[0]
        if app is None:
            if launchKey is not None:
                app = environLocal[launchKey]
            elif self.launchKey is not None:
                launchKey = self.launchKey
                app = environLocal[launchKey]
            else:
                launchKey = environLocal.formatToKey(fmt)
                app = environLocal.formatToApp(fmt)

        platform = common.getPlatform()
        if app is None:
            if platform == 'win':
                # no need to specify application here:
                # windows starts the program based on the file extension
                cmd = 'start %s' % (filePath)
            elif platform == 'darwin':
                cmd = 'open %s %s' % (options, filePath)
            else:
                raise SubConverterException(
                    "Cannot find a valid application path for format {}. "
                    "Specify this in your Environment by calling "
                    "environment.set({!r}, '/path/to/application')".format(
                        fmt, launchKey))
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (app, options, filePath)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s %s' % (app, options, filePath)
        elif platform == 'nix':
            cmd = '%s %s %s' % (app, options, filePath)
        os.system(cmd)
Ejemplo n.º 22
0
 def getSettingsPath(self):
     '''Return the path to the platform specific settings file.
     '''
     platform = common.getPlatform()
     if platform == 'win':
         # try to use defined app data directory for preference file
         # this is not available on all windows versions
         if 'APPDATA' in os.environ.keys():
             dir = os.environ['APPDATA']
         elif ('USERPROFILE' in os.environ.keys() and
             os.path.exists(os.path.join(
             os.environ['USERPROFILE'], 'Application Data'))):
             dir = os.path.join(os.environ['USERPROFILE'], 
                                'Application Data')
         else: # use home directory
             dir = os.path.expanduser('~')       
         return os.path.join(dir, 'music21-settings.xml')
     elif platform in ['nix', 'darwin']:
         # alt : os.path.expanduser('~') 
         dir = os.environ['HOME']
         return os.path.join(dir, '.music21rc')
Ejemplo n.º 23
0
    def launchLaTeX(self, fp = None):
        '''
        converts a .tex file to pdf using lulatex
        Returns the filename with .pdf substituted for .tex
        '''
        platform = common.getPlatform()
        fpApp = self.latexConverter
        options = self.latexOptions
        fpDir = os.path.dirname(fp)
        options += ' --output-dir="' + fpDir + '"'

        if platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin':
            cmd = '%s %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)        
        self.gregorioCommand = cmd
        os.system(cmd)
        newfp = re.sub(r'\.tex', '.pdf', fp)
        return newfp
Ejemplo n.º 24
0
    def launchLaTeX(self, fp = None):
        '''
        converts a .tex file to pdf using lulatex
        Returns the filename with .pdf substituted for .tex
        '''
        platform = common.getPlatform()
        fpApp = self.latexConverter
        options = self.latexOptions
        fpDir = os.path.dirname(fp)
        options += ' --output-dir="' + fpDir + '"'

        if platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, fp)
        elif platform == 'darwin':
            cmd = '%s %s %s' % (fpApp, options, fp)
        elif platform == 'nix':
            cmd = '%s %s %s' % (fpApp, options, fp)        
        self.gregorioCommand = cmd
        os.system(cmd)
        newfp = re.sub(r'\.tex', '.pdf', fp)
        return newfp
Ejemplo n.º 25
0
 def testSearch03(self):
     searchResults = corpus.search('Taiwan', field='locale')
     self.assertEqual(len(searchResults), 27)
     pathInfo = sorted((str(searchResult.sourcePath), searchResult.number)
                       for searchResult in searchResults)
     items = [
         ('essenFolksong/han1.abc', '269'),
         ('essenFolksong/han1.abc', '270'),
         ('essenFolksong/han1.abc', '271'),
         ('essenFolksong/han1.abc', '272'),
         ('essenFolksong/han1.abc', '273'),
         ('essenFolksong/han1.abc', '274'),
         ('essenFolksong/han1.abc', '335'),
         ('essenFolksong/han1.abc', '528'),
         ('essenFolksong/han1.abc', '529'),
         ('essenFolksong/han1.abc', '530'),
         ('essenFolksong/han2.abc', '204'),
         ('essenFolksong/han2.abc', '205'),
         ('essenFolksong/han2.abc', '206'),
         ('essenFolksong/han2.abc', '207'),
         ('essenFolksong/han2.abc', '208'),
         ('essenFolksong/han2.abc', '209'),
         ('essenFolksong/han2.abc', '210'),
         ('essenFolksong/han2.abc', '211'),
         ('essenFolksong/han2.abc', '212'),
         ('essenFolksong/han2.abc', '213'),
         ('essenFolksong/han2.abc', '214'),
         ('essenFolksong/han2.abc', '215'),
         ('essenFolksong/han2.abc', '216'),
         ('essenFolksong/han2.abc', '217'),
         ('essenFolksong/han2.abc', '218'),
         ('essenFolksong/han2.abc', '219'),
         ('essenFolksong/han2.abc', '220'),
     ]
     if common.getPlatform() == 'win':
         expected = [(tup[0].replace('/', '\\'), tup[1]) for tup in items]
     else:
         expected = items
     self.assertEqual(pathInfo, expected)
Ejemplo n.º 26
0
 def getSettingsPath(self):
     platform = common.getPlatform()
     if platform == "win":
         # try to use defined app data directory for preference file
         # this is not available on all windows versions
         if "APPDATA" in os.environ:
             directory = os.environ["APPDATA"]
         elif "USERPROFILE" in os.environ and os.path.exists(
             os.path.join(os.environ["USERPROFILE"], "Application Data")
         ):
             directory = os.path.join(os.environ["USERPROFILE"], "Application Data")
         else:  # use home directory
             directory = os.path.expanduser("~")
         return os.path.join(directory, "music21-settings.xml")
     elif platform in ["nix", "darwin"]:
         # alt : os.path.expanduser('~')
         # might not exist if running as nobody in a webserver...
         if "HOME" in os.environ:
             directory = os.environ["HOME"]
         else:
             directory = "/tmp/"
         return os.path.join(directory, ".music21rc")
Ejemplo n.º 27
0
    def launch(self, fmt, filePath, options='', app=None):
        '''
        DEPRECATED May 24, 2014 -- call Launch on SubConverter

        Needed still just for graphics, graph.launch('png'), lily.translate(), scale
        
        Create a png, svg, etc. converter (or just a graphics converter) and call launch on it
        '''
        # see common.fileExtensions for format names
        m21Format, unused_ext = common.findFormat(fmt)
        environmentKey = self.formatToKey(m21Format)
        if environmentKey is None:
            environmentKey = self.formatToKey(fmt)
        if m21Format == 'vexflow':
            try:
                import webbrowser
                if filePath.find('\\') != -1:
                    pass
                else:
                    if filePath.startswith('/'):
                        filePath = 'file://' + filePath

                webbrowser.open(filePath)
                return
            except ImportError:
                print('Cannot open webbrowser, sorry. Go to file://{}'.format(
                    filePath))
        if app is not None:
            # substitute app provided via argument
            fpApp = app
        elif environmentKey is not None:
            fpApp = self._ref[environmentKey]
        else:
            fpApp = None

        platform = common.getPlatform()
        if fpApp is None:
            if platform == 'win':
                # no need to specify application here:
                # windows starts the program based on the file extension
                cmd = 'start %s' % (filePath)
            elif platform == 'darwin':
                cmd = 'open %s %s' % (options, filePath)
            else:
                if m21Format == 'braille':
                    with open(filePath, 'r') as f:
                        for line in f:
                            print(line, end="")
                        print("")
                    return                    
                else:
                    raise EnvironmentException(
                        "Cannot find a valid application path for format {}. "
                        "Specify this in your Environment by calling "
                        "environment.set({!r}, 'pathToApplication')".format(
                            m21Format, environmentKey))
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, filePath)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s "%s"' % (fpApp, options, filePath)
        elif platform == 'nix':
            cmd = '%s %s "%s"' % (fpApp, options, filePath)
        os.system(cmd)
Ejemplo n.º 28
0
    def launch(self, fmt, filePath, options='', app=None):
        '''
        DEPRECATED May 24, 2014 -- call Launch on SubConverter

        Needed still just for graphics, graph.launch('png'), lily.translate(), scale
        
        Create a png, svg, etc. converter (or just a graphics converter) and call launch on it
        '''
        # see common.fileExtensions for format names
        m21Format, unused_ext = common.findFormat(fmt)
        environmentKey = self.formatToKey(m21Format)
        if environmentKey is None:
            environmentKey = self.formatToKey(fmt)
        if m21Format == 'vexflow':
            try:
                import webbrowser
                if filePath.find('\\') != -1:
                    pass
                else:
                    if filePath.startswith('/'):
                        filePath = 'file://' + filePath

                webbrowser.open(filePath)
                return
            except ImportError:
                print('Cannot open webbrowser, sorry. Go to file://{}'.format(
                    filePath))
        if app is not None:
            # substitute app provided via argument
            fpApp = app
        elif environmentKey is not None:
            fpApp = self._ref[environmentKey]
        else:
            fpApp = None

        platform = common.getPlatform()
        if fpApp is None:
            if platform == 'win':
                # no need to specify application here:
                # windows starts the program based on the file extension
                cmd = 'start %s' % (filePath)
            elif platform == 'darwin':
                cmd = 'open %s %s' % (options, filePath)
            else:
                if m21Format == 'braille':
                    with open(filePath, 'r') as f:
                        for line in f:
                            print(line, end="")
                        print("")
                    return
                else:
                    raise EnvironmentException(
                        "Cannot find a valid application path for format {}. "
                        "Specify this in your Environment by calling "
                        "environment.set({!r}, 'pathToApplication')".format(
                            m21Format, environmentKey))
        elif platform == 'win':  # note extra set of quotes!
            cmd = '""%s" %s "%s""' % (fpApp, options, filePath)
        elif platform == 'darwin':
            cmd = 'open -a"%s" %s "%s"' % (fpApp, options, filePath)
        elif platform == 'nix':
            cmd = '%s %s "%s"' % (fpApp, options, filePath)
        os.system(cmd)
Ejemplo n.º 29
0
    def _loadDefaults(self, forcePlatform=None):
        """
        Load defaults.

        All keys are derived from these defaults.
        """
        # path to a directory for temporary files
        self._ref["directoryScratch"] = None

        # path to lilypond
        self._ref["lilypondPath"] = None

        # version of lilypond
        self._ref["lilypondVersion"] = None
        self._ref["lilypondFormat"] = "pdf"
        self._ref["lilypondBackend"] = "ps"

        # path to a MusicXML reader: default, will find "Finale Notepad"
        self._ref["musicxmlPath"] = None

        # path to a midi reader
        self._ref["midiPath"] = None

        # path to a graphics viewer
        self._ref["graphicsPath"] = None

        # path to a vector graphics viewer
        self._ref["vectorPath"] = None

        # path to a pdf viewer
        self._ref["pdfPath"] = None

        # path to a braille viewer
        self._ref["braillePath"] = None

        # path to MuseScore (if not the musicxmlPath...)
        # for direct creation of PNG from MusicXML
        self._ref["musescoreDirectPNGPath"] = None
        self._ref["showFormat"] = "musicxml"
        self._ref["writeFormat"] = "musicxml"
        self._ref["ipythonShowFormat"] = "ipython.musicxml.png"

        self._ref["autoDownload"] = "ask"
        self._ref["debug"] = 0

        # printing of missing import warnings
        # default/non-zero is on
        self._ref["warnings"] = 1

        # store a list of strings
        self._ref["localCorpusSettings"] = []
        self._ref["localCorporaSettings"] = {}

        self._ref["manualCoreCorpusPath"] = None

        if forcePlatform is None:
            platform = common.getPlatform()
        else:
            platform = forcePlatform

        if platform == "win":
            for name, value in [
                ("lilypondPath", "lilypond"),
                ("musescoreDirectPNGPath", common.cleanpath(r"%PROGRAMFILES(x86)%\MuseScore 2\MuseScore.exe")),
            ]:
                self.__setitem__(name, value)  # use for key checking
        elif platform == "nix":
            for name, value in [("lilypondPath", "lilypond")]:
                self.__setitem__(name, value)  # use for key checking
        elif platform == "darwin":
            for name, value in [
                ("lilypondPath", "/Applications/Lilypond.app/Contents/Resources/bin/lilypond"),
                ("musicxmlPath", "/Applications/Finale Notepad 2014.app"),
                ("graphicsPath", "/Applications/Preview.app"),
                ("vectorPath", "/Applications/Preview.app"),
                ("pdfPath", "/Applications/Preview.app"),
                ("midiPath", "/Applications/QuickTime Player.app"),
                ("musescoreDirectPNGPath", "/Applications/MuseScore 2.app/Contents/MacOS/mscore"),
            ]:
                self.__setitem__(name, value)  # use for key checking
Ejemplo n.º 30
0
def main(fnAccept=None):
    '''
    `fnAccept` is a list of one or more files to test.
    '''
    sourceFolder = common.getSourceFilePath()
    mg = test.ModuleGather()
    print(
        "If you get an error, make sure that 'sudo pip install pylint' is there"
    )

    # only accept a few file names for now
    if fnAccept in (None, []):
        fnAccept = ['stream']
    fnPathReject = [
        '/ext/',
        'bar.py',  # crashes pylint...
        'repeat.py',  # hangs pylint...
        'spanner.py',  # hangs pylint...
    ]
    #fnAccept = ['stream.py', 'note.py', 'chord.py']
    disable = [
        #'C0301', 'C0302', 'C0103', 'C0330', 'C0324',
        #'W0621', 'W0511',
        #'W0404', 'R0201', 'R0904', 'E1101', 'R0914', 'R0903',
        #'R0911', 'R0902',
        'unnecessary-pass',  # nice, but not really a problem...
        'locally-disabled',  # test for this later, but hopefully will know what they're doing
        'arguments-differ',  # someday...
        'abstract-class-instantiated',  # this trips on the fractions.Fraction() class.
        'redefined-builtin',  # remove when Eclipse tags are parsed @ReservedAssignment = pylint: disable=W0622
        'fixme',  # known...
        'superfluous-parens',  # next...
        'too-many-statements',  # someday
        'no-member',  # important, but too many false positives
        'too-many-arguments',  # definitely! but takes too long to get a fix now...
        'too-many-public-methods',  # maybe, look 
        'too-many-branches',  # yes, someday
        'too-many-locals',  # no
        'too-many-lines',  # yes, someday.
        'bad-whitespace',  # maybe later, but "bad" isn't something I necessarily agree with
        'bad-continuation',  # never remove -- this is a good thing many times.
        'line-too-long',  # maybe later
        'too-many-return-statements',  # we'll see
        'unpacking-non-sequence',  # gets it wrong too often.
        'too-many-instance-attributes',  # maybe later
        'invalid-name',  # never remove -- these are good music21 names; fix the regexp instead...
        'no-self-use',  # maybe later
        'too-few-public-methods',  # never remove or set to 1
        'trailing-whitespace',  # should ignore blank lines with tabs
        'missing-docstring',  # gets too many well-documented properties
        'star-args',  # no problem with them...
        'protected-access',  # this is an important one, but for now we do a lot of
        # x = copy.deepcopy(self); x._volume = ... which is not a problem...
        'unused-argument',
        'import-self',  # fix is either to get rid of it or move away many tests...
    ]

    cmd = [
        '/usr/bin/env pylint -f colorized ' +
        '--dummy-variables-rgx="_|dummy|unused|i|j|junk" ' +
        '--docstring-min-length=3 ' +
        '--max-args=7 ' +  # should be 5 later, but baby steps
        '--bad-name="foo,shit,f**k,stuff" '  # definitely allow "bar" for barlines
    ]
    for pyLintId in disable:
        cmd.append('--disable=%s' % pyLintId)

    # add entire package
    for fp in mg.modulePaths:
        rejectIt = False
        for rejectPath in fnPathReject:
            if rejectPath in fp:
                rejectIt = True
                break
        if rejectIt:
            continue
        fpRelative = fp.replace(sourceFolder, '')
        unused_dir, fn = os.path.split(fpRelative)
        fnNoExt = fn.replace('.py', '')
        fpRelativeNoSlash = fpRelative[1:]
        if fn in fnAccept or fnNoExt in fnAccept or fpRelative in fnAccept or fpRelativeNoSlash in fnAccept:
            cmdFile = cmd + [fp]
            print(' '.join(cmdFile))
            if common.getPlatform() != 'win':
                os.system(' '.join(cmdFile))
Ejemplo n.º 31
0
def main(fnAccept=None):
    '''
    `fnAccept` is a list of one or more files to test.
    '''
    sourceFolder = common.getSourceFilePath()
    mg = test.ModuleGather()
    print("If you get an error, make sure that 'sudo pip install pylint' is there")

    # only accept a few file names for now
    if fnAccept in (None, []):
        fnAccept = ['stream']
    fnPathReject = ['/ext/',
                    'bar.py',  # crashes pylint...
                    'repeat.py', # hangs pylint...
                    'spanner.py', # hangs pylint...
                    ]
        #fnAccept = ['stream.py', 'note.py', 'chord.py']
    disable = [
                #'C0301', 'C0302', 'C0103', 'C0330', 'C0324', 
                #'W0621', 'W0511', 
                #'W0404', 'R0201', 'R0904', 'E1101', 'R0914', 'R0903',
                #'R0911', 'R0902', 
                'unnecessary-pass', # nice, but not really a problem...
                'locally-disabled', # test for this later, but hopefully will know what they're doing

                'arguments-differ', # someday...
                'abstract-class-instantiated', # this trips on the fractions.Fraction() class.
                'redefined-builtin', # remove when Eclipse tags are parsed @ReservedAssignment = pylint: disable=W0622
                'fixme', # known...
                'superfluous-parens', # next...
                'too-many-statements', # someday
                'no-member', # important, but too many false positives
                'too-many-arguments', # definitely! but takes too long to get a fix now...
                'too-many-public-methods', # maybe, look 
                'too-many-branches', # yes, someday
                'too-many-locals',   # no
                'too-many-lines',    # yes, someday.
                'bad-whitespace',    # maybe later, but "bad" isn't something I necessarily agree with
                'bad-continuation',  # never remove -- this is a good thing many times.
                'line-too-long',     # maybe later
                'too-many-return-statements', # we'll see
                'unpacking-non-sequence', # gets it wrong too often.
                'too-many-instance-attributes', # maybe later
                
                'invalid-name',      # never remove -- these are good music21 names; fix the regexp instead...
                'no-self-use',       # maybe later
                'too-few-public-methods', # never remove or set to 1
                'trailing-whitespace',  # should ignore blank lines with tabs
                'missing-docstring',    # gets too many well-documented properties
                'star-args', # no problem with them...
                'protected-access', # this is an important one, but for now we do a lot of
                           # x = copy.deepcopy(self); x._volume = ... which is not a problem...
                'unused-argument',
                'import-self', # fix is either to get rid of it or move away many tests...
               ]

    cmd = ['/usr/bin/env pylint -f colorized ' +
           '--dummy-variables-rgx="_|dummy|unused|i|j|junk" ' + 
           '--docstring-min-length=3 ' +
           '--max-args=7 ' +  # should be 5 later, but baby steps
           '--bad-name="foo,shit,f**k,stuff" ' # definitely allow "bar" for barlines
           ]
    for pyLintId in disable:
        cmd.append('--disable=%s' % pyLintId)

    # add entire package
    for fp in mg.modulePaths:
        rejectIt = False
        for rejectPath in fnPathReject:
            if rejectPath in fp:
                rejectIt = True
                break
        if rejectIt:
            continue
        fpRelative = fp.replace(sourceFolder, '')
        unused_dir, fn = os.path.split(fpRelative)
        fnNoExt = fn.replace('.py', '')
        fpRelativeNoSlash = fpRelative[1:]
        if fn in fnAccept or fnNoExt in fnAccept or fpRelative in fnAccept or fpRelativeNoSlash in fnAccept:
            cmdFile = cmd + [fp]
            print(' '.join(cmdFile))
            if common.getPlatform() != 'win':
                os.system(' '.join(cmdFile))