예제 #1
0
 def __enter__(self):
     from System import Environment
     if self._prepend:
         Environment.SetEnvironmentVariable(
             self._variable,
             "%s%s%s" % (self._value, self._sep, self._oldval))
     else:
         Environment.SetEnvironmentVariable(self._variable, self._value)
    def getAERenderOnlyFileName(self):
        # Get the path to the text file that forces After Effects to run in Render Engine mode.
        outputPath = os.path.join(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
            "ae_render_only_node.txt")
        if SystemUtils.IsRunningOnMac():
            outputPath = os.path.join(
                Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                "Documents/ae_render_only_node.txt")

        return outputPath
예제 #3
0
파일: method.py 프로젝트: zuvys/ironpython3
def test_from_cmdline():
    '''
    '''
    from iptest.console_util import IronPythonInstance
    from sys import executable, exec_prefix
    from System import Environment

    extraArgs = ""
    if "-X:PreferComInteropAssembly" in Environment.GetCommandLineArgs():
        extraArgs += "-X:PreferComInteropAssembly"

    #Does it work from the commandline with positive cases?
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    try:
        ipi.ExecuteLine("from System import Type, Activator")
        ipi.ExecuteLine(
            "com_obj = Activator.CreateInstance(Type.GetTypeFromProgID('DlrComLibrary.DlrUniversalObj'))"
        )

        #Dev10 409941
        Assert("System.__ComObject" in ipi.ExecuteLine("print com_obj"))
        AreEqual(ipi.ExecuteLine("print com_obj.m0()"), "None")
    finally:
        ipi.End()
예제 #4
0
    def __initialize(cls):

        # get the basic locations that the other locations build on
        script_dir = Directory.GetParent(__file__).FullName
        profile_dir = Environment.GetFolderPath(
           Environment.SpecialFolder.ApplicationData) + \
           r"\Comic Vine Scraper"

        # set the standard locations for settings files
        cls.SETTINGS_FILE = profile_dir + r'\settings.dat'
        cls.ADVANCED_FILE = profile_dir + r'\advanced.dat'
        cls.GEOMETRY_FILE = profile_dir + r'\geometry.dat'
        cls.SERIES_FILE = profile_dir + r'\series.dat'
        cls.LOCAL_CACHE_DIRECTORY = profile_dir + r'\localCache'
        cls.I18N_DEFAULTS_FILE = script_dir + r"\en.zip"

        # do a special trick to things run from within the IDE,
        # where certain files like 'en.zip' are in different locations
        ide_i18n_file = Directory.GetParent(
           Directory.GetParent( script_dir).FullName ).FullName + \
           r'\src\resources\languages\en.zip'
        if not File.Exists(cls.I18N_DEFAULTS_FILE) \
              and File.Exists( ide_i18n_file ):
            cls.I18N_DEFAULTS_FILE = ide_i18n_file

        # import settings from legacy location, if needed.
        # ensure profile directory exists.
        cls.__import_legacy_settings(script_dir, profile_dir)
        if not File.Exists(profile_dir):
            Directory.CreateDirectory(profile_dir)
예제 #5
0
    def test_S(self):
        """Test the -S (suppress site initialization) option."""

        # Create a local site.py that sets some global context. Do this in a temporary directory to avoid accidently
        # overwriting a real site.py or creating confusion. Use the IRONPYTHONPATH environment variable to point
        # IronPython at this version of site.py.
        from System import Environment
        with open(os.path.join(self.tmpdir, "site.py"), "w") as f:
            f.write("import sys\nsys.foo = 123\n")

        with IronPythonVariableContext("IRONPYTHONPATH",
                                       self.tmpdir,
                                       prepend=True):
            print(Environment.GetEnvironmentVariable("IRONPYTHONPATH"))
            # Verify that the file gets loaded by default.
            self.TestCommandLine(("-c", "import sys; print(sys.foo)"), "123\n")

            # CP778 - verify 'site' does not show up in dir()
            self.TestCommandLine(("-c", "print('site' in dir())"), "False\n")

            # Verify that Lib remains in sys.path.
            self.TestCommandLine((
                "-S", "-c",
                "import os ; import sys; print(str(os.path.join(sys.exec_prefix, 'Lib')).lower() in [x.lower() for x in sys.path])"
            ), "True\n")

            # Now check that we can suppress this with -S.
            self.TestCommandLine(
                ("-S", "-c", "import sys; print(sys.foo)"),
                ("lastline",
                 "AttributeError: 'module' object has no attribute 'foo'\n"),
                1)
예제 #6
0
 def __init__(self, variable, value, sep=os.pathsep, prepend=False):
     from System import Environment
     self._variable = variable
     self._value = value
     self._prepend = prepend
     self._sep = sep
     self._oldval = Environment.GetEnvironmentVariable(self._variable)
예제 #7
0
def unmanagedDLL():
    '''
    Places an unmanaged DLL inside DLLs.
    '''
    twain = Environment.GetEnvironmentVariable("SystemRoot") + "\\twain.dll"
    File.Copy(twain,
              DLLS_DIR + "\\twain.dll")
예제 #8
0
    def setUp(self):
        temp_dir = DirectoryInfo(Environment.GetEnvironmentVariable("TEMP"))
        #       myDocuments = DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
        self.temp_dir = temp_dir.CreateSubdirectory('tempDir')
        self.temp_dir_path = self.temp_dir.ToString()

        self.file1 = FileInfo(self.temp_dir_path + '\\file1.txt')
        self.file2 = FileInfo(self.temp_dir_path + '\\file2.txt')
        self.file3 = FileInfo(self.temp_dir_path + '\\file3.txt')

        sw = self.file1.CreateText()
        sw.WriteLine("Hello1")
        sw.Close()

        sw = self.file2.CreateText()
        sw.WriteLine("Hello2")
        sw.Close()

        sw = self.file3.CreateText()
        sw.WriteLine("Hello3")
        sw.Close()

        today = DateTime.Now
        one_day_old = today.AddDays(-1).ToString("yyyy.MM.dd")
        two_days_old = today.AddDays(-2).ToString("yyyy.MM.dd")
        self.file1.CreationTime = DateTime.Parse(today.ToString("yyyy.MM.dd"))
        self.file2.CreationTime = DateTime.Parse(one_day_old)
        self.file3.CreationTime = DateTime.Parse(two_days_old)

        print "\r myDocuments temp path = [%s]" % self.temp_dir_path
        print "CreationTime file1 = [%s]" % self.file1.CreationTime
        print "CreationTime file2 = [%s]" % self.file2.CreationTime
        print "CreationTime file3 = [%s]" % self.file3.CreationTime
예제 #9
0
def systemInfo():
    verInfo = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
    psKey = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine"
    sysPolKey = r"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System"

    sysSummary = printHeader("SYSTEM INFORMATION")
    sysSummary += "{0:<10}: {1}\n".format("Host", Env.MachineName)
    sysSummary += "{0:<10}: {1} {2}\n".format("OS", Registry.GetValue(verInfo, "ProductName", "Windows"), Diagnostics.FileVersionInfo.GetVersionInfo(Env.SystemDirectory + "\\kernel32.dll").ProductVersion)
    sysSummary += "{0:<10}: {1}\n".format("64-Bit", Env.Is64BitOperatingSystem)
    sysSummary += "{0:<10}: {1}\n".format("Date", DateTime.Now.ToString())
    sysSummary += "{0:<10}: {1}\n\n".format("Uptime", DateTimeOffset(DateTime.Now).AddMilliseconds(-Env.TickCount).LocalDateTime)
    
    sysSummary += "{0:<14}: {1}\{2}\n".format("Username", Env.UserDomainName, Env.UserName)
    sysSummary += "{0:<14}: {1}\n\n".format("Logon Server", Env.GetEnvironmentVariable("LOGONSERVER"))

    sysSummary += "{0:<22}: {1}\n".format("PowerShell Version", Registry.GetValue(psKey, "PowerShellVersion", "N/A - Likely 2.0"))
    sysSummary += "{0:<22}: {1}\n".format("PowerShell Compat", Registry.GetValue(psKey, "PSCompatibleVersion", "N/A - Likely 1.0, 2.0"))
    sysSummary += "{0:<22}: {1}\n".format("PS Script Block Log", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging", "EnableScriptBlockLogging", "N/A"))
    sysSummary += "{0:<22}: {1}\n".format("PS Transcription", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription", "EnableTranscripting", "N/A"))
    sysSummary += "{0:<22}: {1}\n".format("PS Transcription Dir", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription", "OutputDirectory", "N/A"))
    sysSummary += "{0:<22}: {1}\n\n".format("PS Module Logging", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging", "EnableModuleLogging", "N/A"))

    sysSummary += "{0:<27}: {1}\n".format("UAC Enabled", Convert.ToBoolean(Registry.GetValue(sysPolKey, "EnableLUA", "N/A")))
    sysSummary += "{0:<27}: {1}\n".format("High Integrity", WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
    sysSummary += "{0:<27}: {1}\n".format("UAC Token Filter Disabled", Registry.GetValue(sysPolKey, "LocalAccount", False))
    sysSummary += "{0:<27}: {1}\n".format("UAC Admin Filter Enabled", Registry.GetValue(sysPolKey, "FilterAdministratorToken", False))
    sysSummary += "{0:<27}: {1}\n".format("Local Admin Pass Solution", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft Services\AdmPwd", "AdmPwdEnabled", "N/A"))
    sysSummary += "{0:<27}: {1}\n".format("LSASS Protection", Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa", "RunAsPPL", "N/A"))
    sysSummary += "{0:<27}: {1}\n".format("Deny RDP Connections", Convert.ToBoolean(Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server", "FDenyTSConnections", "N/A")))

    return sysSummary
예제 #10
0
파일: method.py 프로젝트: zuvys/ironpython3
def test_from_cmdline_neg():
    '''
    '''
    from iptest.console_util import IronPythonInstance
    from sys import executable, exec_prefix
    from System import Environment

    extraArgs = ""
    if "-X:PreferComInteropAssembly" in Environment.GetCommandLineArgs():
        extraArgs += "-X:PreferComInteropAssembly"

    #Does it work from the commandline with negative cases?
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    try:
        ipi.ExecuteLine("from System import Type, Activator")
        ipi.ExecuteLine("import sys")
        ipi.ExecuteLine(
            "com_obj = Activator.CreateInstance(Type.GetTypeFromProgID('DlrComLibrary.DlrUniversalObj'))"
        )
        ipi.ExecuteLine("sys.stderr = sys.stdout"
                        )  #Limitation of ipi.  Cannot get sys.stderr...
        response = ipi.ExecuteLine("com_obj.m0(3)")
        Assert("Does not support a collection." in response)  #Merlin 324233
        Assert("EnvironmentError:" in response)  #Merlin 324233

    finally:
        ipi.End()
def _pick_sound_file(title, local_path):
    dialog = OpenFileDialog()
    dialog.Title = title
    dialog.InitialDirectory = Environment.GetEnvironmentVariable("USERPROFILE")
    dialog.Filter = "mp3 files (*.mp3)|*.mp3"
    if dialog.ShowDialog() == DialogResult.OK:
        os.system('copy "{0}" "{1}"'.format(dialog.FileName, local_path))
        Parent.PlaySound(local_path, 1)
예제 #12
0
def browserEnum():
    summary = printHeader("BROWSER ENUM")
    regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?')

    #Active IE Urls
    summary += printSubheader("ACTIVE EXPLORER URLS")
    app = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))
    summary += "\n".join([w.LocationUrl() for w in app.Windows()])

    #Chrome History
    summary += printSubheader("\n\nChrome History")
    try:
        cHistPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\History".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName)
        cHist = open(cHistPath, "r").read()
        summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(cHist)][-10:])
    except:
        pass

    summary += printSubheader("\nChrome Bookmarks")
    #Chrome Bookmarks
    try:
        cBMPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\Bookmarks".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName)
        js = JavaScriptSerializer()
        cBM = js.DeserializeObject(open(cBMPath, "r").read())
        urls = cBM["roots"]["bookmark_bar"]["children"]
        for url in urls:
            u = url['url']
            d = url['name']
            summary += "[*] {0}\n{1}\n\n".format(d, u)
    except:
        pass

    summary += printSubheader("Firefox History")
    #Firefox History
    try:
        regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?')
        fHistPath = "{0}\Users\{1}\AppData\Roaming\Mozilla\Firefox\Profiles".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName)
        for path in DirectoryInfo(fHistPath).EnumerateDirectories("*.default"):
            places = open(path.FullName + "\places.sqlite", "r").read()
            summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(places)][:10])
    except:
        pass

    summary += printSubheader("IE History")
    typedUrlPath = "\Software\Microsoft\Internet Explorer\TypedURLs"
    for sid in Registry.Users.GetSubKeyNames():
        if sid != ".DEFAULT" and not sid.endswith("Classes"):
            try:
                typedUrlsKey = Registry.Users.OpenSubKey(sid + typedUrlPath)
                if typedUrlsKey != None:
                    summary += "[{0}][{1}]\n".format(sid, SecurityIdentifier(sid.ToString()).Translate(NTAccount))
                    for value in typedUrlsKey.GetValueNames():
                        summary += "\t{0}\n".format(typedUrlsKey.GetValue(value))
                summary += "\n"
            except SystemError:
                pass

    return summary    
예제 #13
0
def HandleExportHeatSource(sender, args):
    NewFileLocation = r"C:\Users"

    dialog = SaveFileDialog()
    dialog.Title = "Export heat source"

    dialog.FileName = "{0}mm_{1}cm-min.xml".format(
        beadSizeInput.Text.replace('.', ','),
        travelSpeedInput.Text.replace('.', ','))
    dialog.Filter = "XML Files|*.xml"
    dialog.InitialDirectory = Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments)

    if dialog.ShowDialog():
        NewFileLocation = dialog.FileName
        file_path = os.path.dirname(os.path.realpath(__file__))
        HeatSourceFile = os.path.join(file_path, 'Heat-source_Power.xml')

        RequiredPower, _ = ReqPowerText.Text.split(' kJ')
        FrontLength, _ = FLEstimate.Text.split(' mm')
        RearLength, _ = RLEstimate.Text.split(' mm')
        WidthLength, _ = WidthEstimate.Text.split(' mm')
        DepthLength, _ = DepthEstimate.Text.split(' mm')

        with open(NewFileLocation, 'w') as NewHeatSource:
            with open(HeatSourceFile, 'r') as Template:
                for line in Template:
                    if "<comment>" in line:
                        line = "<comment>{0}</comment>".format(
                            "Generated by MSC Apex welding toolkit")
                    if "<velocity dimension=" in line:
                        line = '<velocity dimension="7" unit="8">{0}</velocity>'.format(
                            travelSpeedInput.Text)
                    if "<power dimension=" in line:
                        line = '<power dimension="12" unit="0">{0}</power>'.format(
                            RequiredPower)
                    if "<efficiency>" in line:
                        line = '<efficiency>{0}</efficiency>'.format(
                            effParamInput.Text)
                    if "<front_length" in line:
                        line = '<front_length dimension="5" unit="2" value="{0}"/>'.format(
                            FrontLength)
                    if '<rear_length' in line:
                        line = '<rear_length dimension="5" unit="2" value="{0}"/>'.format(
                            RearLength)
                    if '<width dimension' in line:
                        line = '<width dimension="5" unit="2" value="{0}"/>'.format(
                            WidthLength)
                    if '<depth dimension' in line:
                        line = '<depth dimension="5" unit="2" value="{0}"/>'.format(
                            DepthLength)
                    NewHeatSource.write(line)
예제 #14
0
def OpenAndActivateBatchRvtTemporaryDocument(uiApplication):
    application = uiApplication.Application
    BATCHRVT_TEMPORARY_REVIT_FILE_PATH = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "BatchRvt", "TemporaryProject." + application.VersionNumber + ".rvt")
    if not path_util.FileExists(BATCHRVT_TEMPORARY_REVIT_FILE_PATH):
        path_util.CreateDirectoryForFilePath(
            BATCHRVT_TEMPORARY_REVIT_FILE_PATH)
        newDoc = CreateNewProjectFile(application,
                                      BATCHRVT_TEMPORARY_REVIT_FILE_PATH)
        newDoc.Close(False)
    uiDoc = uiApplication.OpenAndActivateDocument(
        BATCHRVT_TEMPORARY_REVIT_FILE_PATH)
    return uiDoc
예제 #15
0
def interestingFiles():
    filetypes = [ "*.ps1", "*pass*", "*diagram*", "*.pdf", "*.vsd", "*.doc", "*.docx", "*.xls", "*.xlsx", "*.kdbx", "*.key", "KeePass.config"]
    dirs = [
        Env.GetEnvironmentVariable("ProgramFiles"),
        Env.GetEnvironmentVariable("ProgramFiles(x86)"),
        Env.GetEnvironmentVariable("USERPROFILE") + "\Desktop",
        Env.GetEnvironmentVariable("USERPROFILE") + "\Documents",
    ]

    
    indexedFiles()
    filesSummary = printHeader("INTERESTING FILES")
    filesSummary += printSubheader ("Logical Drives")
    for drive in DriveInfo.GetDrives():
        try:
            filesSummary += "Drive {0}\n".format(drive.Name)
            filesSummary += "\tDrive Type: {0}\n".format(drive.DriveType)
            filesSummary += "\tVolume label: {0}\n".format(drive.VolumeLabel)
            filesSummary += "\tFile System: {0}\n".format(drive.DriveFormat)
            filesSummary += "\tAvailable Space for user: \t{0}\n".format(drive.AvailableFreeSpace)
            filesSummary += "\tTotal Available Space: \t\t{0}\n".format(drive.TotalFreeSpace)
            filesSummary += "\tTotal Drive Space: \t\t{0}\n".format(drive.TotalSize)
        except IOError:
            continue

    filesSummary += printSubheader ("DIRECTORY LISTINGS")
    for dir in dirs:
        dirInfo = DirectoryInfo(dir)
        filesSummary += dir + "\n"
        for d in dirInfo.GetDirectories():
            filesSummary += "  " + d.Name + "\n"
        filesSummary += "\n"

    filesSummary += printSubheader ("FILES BY EXTENSION")
    profile = DirectoryInfo(Env.GetEnvironmentVariable("USERPROFILE"))
    for t in filetypes:
        filesSummary = recursiveFiles(profile, t, filesSummary)

    filesSummary += printSubheader ("POWERSHELL HISTORY")
    psHistFile = Env.GetEnvironmentVariable("APPDATA") + "\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt"
    try:
        history = open(psHistFile, "r").readlines()[-50:]
        filesSummary += "".join(history)
    except IndexError:
        history = open(psHistFile, "r").readlines()
        filesSummary += "".join(history)
    except IOError:
        filesSummary += "No history!\n"

    filesSummary += printSubheader ("HOSTS FILE")
    filesSummary += open(Env.GetEnvironmentVariable("WINDIR") + "\System32\drivers\etc\hosts", "r").read()
    return filesSummary 
예제 #16
0
def HandleExportHeatSource(sender, args):
    NewFileLocation = r"C:\Users"

    dialog = SaveFileDialog()
    dialog.Title = "Export heat source"

    dialog.FileName = "{0}cm-min_{1}A_{2}V.xml".format(travelSpeedInput.Text,
                                                       elecCurrentInput.Text,
                                                       elecVoltageInput.Text)
    dialog.Filter = "XML Files|*.xml"
    dialog.InitialDirectory = Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments)

    if dialog.ShowDialog():
        NewFileLocation = dialog.FileName
        file_path = os.path.dirname(os.path.realpath(__file__))
        HeatSourceFile = os.path.join(file_path, 'Heat-source.xml')
        with open(NewFileLocation, 'w') as NewHeatSource:
            with open(HeatSourceFile, 'r') as Template:
                for line in Template:
                    if "<comment>" in line:
                        line = "<comment>{0}</comment>".format(
                            "Generated by MSC Apex welding toolkit")
                    if "<velocity dimension=" in line:
                        line = '<velocity dimension="7" unit="8">{0}</velocity>'.format(
                            travelSpeedInput.Text)
                    if "<voltage dimension=" in line:
                        line = '<voltage dimension="20" unit="0">{0}</voltage>'.format(
                            elecVoltageInput.Text)
                    if "<current dimension=" in line:
                        line = '<current dimension="2" unit="0">{0}</current>'.format(
                            elecCurrentInput.Text)
                    if "<efficiency>" in line:
                        line = '<efficiency>{0}</efficiency>'.format(
                            effParamInput.Text)
                    if "<front_length" in line:
                        line = '<front_length dimension="5" unit="2" value="{0}"/>'.format(
                            FLEstimate.Text)
                    if '<rear_length' in line:
                        line = '<rear_length dimension="5" unit="2" value="{0}"/>'.format(
                            RLEstimate.Text)
                    if '<width dimension' in line:
                        line = '<width dimension="5" unit="2" value="{0}"/>'.format(
                            WidthEstimate.Text)
                    if '<depth dimension' in line:
                        line = '<depth dimension="5" unit="2" value="{0}"/>'.format(
                            DepthEstimate.Text)
                    NewHeatSource.write(line)
예제 #17
0
 def setUp(self):
     self.temp_directory = Env.GetEnvironmentVariable("TEMP")
     #check temp dir exists
     self.assertTrue(Directory.Exists(self.temp_directory))
     #check temp file in temp dir does not exist
     if File.Exists(self.tempFileFullPath1 or self.tempFileFullPath2
                    or self.tempFileFullPath1):
         File.Delete(self.tempFileFullPath1)
         File.Delete(self.tempFileFullPath2)
         File.Delete(self.tempFileFullPath3)
     #create a file to check and delete
     fs1 = FileStream(self.tempFileFullPath1, FileMode.Create)
     fs2 = FileStream(self.tempFileFullPath2, FileMode.Create)
     fs3 = FileStream(self.tempFileFullPath3, FileMode.Create)
     fs1.Close()
     fs2.Close()
     fs3.Close()
예제 #18
0
파일: exportIFC.py 프로젝트: karthi1015/bim
def exportNWD(filePath, expPath, viewName):
    err = checkInput(filePath)
    if err:
        return ("Invalid path")
    app = DocMgr.Instance.CurrentUIApplication.Application
    modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath)
    openOpts = OpenOptions()
    wsConfig = WorksetConfiguration(WorksetConfigurationOption.OpenAllWorksets)
    openOpts.SetOpenWorksetsConfiguration(wsConfig)
    doc = app.OpenDocumentFile(modelPath, openOpts)
    expView = findNwdView(doc, viewName)
    expOpts = setupExpOptions(expView)
    if expPath == None:
        expPath = Environment.GetFolderPath(
            Environment.SpecialFolder.MyDocuments)
    doc.Export(expPath, String.Empty, expOpts)
    doc.Close(False)
    return (filePath)
예제 #19
0
def loadMasterPluginIndex():
    """ Loads the Master Plugin Index List into a map
	"""
    import System
    from System.IO import Path
    from System import Environment
    file = Path.Combine(
        Environment.GetFolderPath(
            Environment.SpecialFolder.LocalApplicationData), 'Skyrim',
        'plugins.txt')
    with open(file, "rt") as f:
        first = f.readline().strip().lower()
        offset = first != 'skyrim.esm' and 1 or 0
        masterIdx = dict([(r.strip().lower(), i + offset)
                          for i, r in enumerate(f.readlines())])
        masterIdx[first] = offset
        if offset: masterIdx['skyrim.esm'] = 0
    return masterIdx
예제 #20
0
def try_get_plugin_path(plugin):
    """Try to get path to plugin folder."""
    clr.AddReference('ProtoGeometry')
    _loc = tuple(a.Location
                 for a in AppDomain.CurrentDomain.GetAssemblies()
                 if 'ProtoGeometry' in a.FullName)

    try:
        _ver = float(_loc[0].split('\\')[-2])
    except:
        _ver = float(_loc[0].split('\\')[-2].split(' ')[-1])

    assert _ver >= 1.2, 'You need Dynamo 1.2 or higher to use this plugin!'

    _appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    _dynamo_path = '\\'.join(_loc[0].split('\\')[-4:-1])
    # if the assembly is cached put Revit folder first, and then try to load it from core
    _dynamo_paths = (_dynamo_path.replace('Dynamo Core', 'Dynamo Revit'),
                    _dynamo_path.replace('Dynamo Revit', 'Dynamo Core'))
    _settings_filename = 'DynamoSettings.xml'

    pkf = []
    for path in _dynamo_paths:
        settings_file = IO.Path.Combine(_appdata, path, _settings_filename)
        if IO.File.Exists(settings_file):
            with open(settings_file, 'rb') as outf:
                for line in outf:
                    if line.strip().startswith('<CustomPackageFolders>'):
                        for l in outf:
                            if l.strip().startswith('</CustomPackageFolders>'):
                                break
                            else:
                                pkf.append(l.replace('</string>', '').replace('<string>', '').strip())

    for p in pkf:
        pp = IO.Path.Combine(p, 'packages', plugin, 'extra')
        # In case of custom folders user may put honeybee under the root folder
        ppp = IO.Path.Combine(p, plugin, 'extra')
        if IO.Directory.Exists(pp):
            return pp
        elif IO.Directory.Exists(ppp):
            return ppp
예제 #21
0
def RunCommand():
    file_name = ""

    bitmap = doc.Views.ActiveView.CaptureToBitmap(True, True, True)

    # copy bitmap to clipboard
    Clipboard.SetImage(bitmap)

    # save bitmap to file
    save_file_dialog = Rhino.UI.SaveFileDialog()
    save_file_dialog.Filter = "*.bmp"
    save_file_dialog.InitialDirectory = \
      Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

    if save_file_dialog.ShowDialog() == DialogResult.OK:
        file_name = save_file_dialog.FileName

    if file_name != "":
        bitmap.Save(file_name)

    return Rhino.Commands.Result.Success
예제 #22
0
class Test(unittest.TestCase):

    temp_directory = Env.GetEnvironmentVariable("TEMP")
    temp_file1 = r"\test1.test"
    temp_file2 = r"\test2.test"
    temp_file3 = r"\test3.test"
    tempFileFullPath1 = temp_directory + temp_file1
    tempFileFullPath2 = temp_directory + temp_file2
    tempFileFullPath3 = temp_directory + temp_file3

    def setUp(self):
        self.temp_directory = Env.GetEnvironmentVariable("TEMP")
        #check temp dir exists
        self.assertTrue(Directory.Exists(self.temp_directory))
        #check temp file in temp dir does not exist
        if File.Exists(self.tempFileFullPath1 or self.tempFileFullPath2
                       or self.tempFileFullPath1):
            File.Delete(self.tempFileFullPath1)
            File.Delete(self.tempFileFullPath2)
            File.Delete(self.tempFileFullPath3)
        #create a file to check and delete
        fs1 = FileStream(self.tempFileFullPath1, FileMode.Create)
        fs2 = FileStream(self.tempFileFullPath2, FileMode.Create)
        fs3 = FileStream(self.tempFileFullPath3, FileMode.Create)
        fs1.Close()
        fs2.Close()
        fs3.Close()

    def tearDown(self):
        self.assertFalse(File.Exists(self.tempFileFullPath1))
        self.assertFalse(File.Exists(self.tempFileFullPath2))
        self.assertFalse(File.Exists(self.tempFileFullPath3))

    def testDeleteAFile(self):
        #        File.Delete(self.tempFileFullPath1)
        deleteFiles.deleteFilesFromDirectoryWithExtension(
            self.temp_directory, "test")
        self.assertFalse(File.Exists(self.tempFileFullPath1))
        self.assertFalse(File.Exists(self.tempFileFullPath2))
        self.assertFalse(File.Exists(self.tempFileFullPath3))
예제 #23
0
    def test_dispatch_to_ReflectOptimized(self):
        """dispatch to a ReflectOptimized method"""

        from iptest.console_util import IronPythonInstance
        from System import Environment
        from sys import executable
        
        wkdir = self.test_dir
        
        if "-X:LightweightScopes" in Environment.GetCommandLineArgs():
            ipi = IronPythonInstance(executable, wkdir, "-X:LightweightScopes", "-X:BasicConsole")
        else:
            ipi = IronPythonInstance(executable, wkdir, "-X:BasicConsole")

        if (ipi.Start()):
            try:
                result = ipi.ExecuteLine("from iptest.ipunittest import load_ironpython_test")
                result = ipi.ExecuteLine("load_ironpython_test()")
                result = ipi.ExecuteLine("from IronPythonTest import DefaultParams")
                response = ipi.ExecuteLine("DefaultParams.FuncWithDefaults(1100, z=82)")
                self.assertEqual(response, '1184')
            finally:
                ipi.End()
예제 #24
0
import clr
from System import Environment
OUT = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
예제 #25
0
def GetLocalAppDataFolderPath():
    return Environment.GetFolderPath(
        Environment.SpecialFolder.LocalApplicationData)
예제 #26
0
def GetUserDesktopFolderPath():
    return Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
예제 #27
0
 def __exit__(self, *args):
     from System import Environment
     Environment.SetEnvironmentVariable(self._variable, self._oldval)
예제 #28
0
							else:						
								logger.fatal(output.getvalue())
						output.close()


		
if __name__ == '__main__':
	etl_logger = None
	emailed =0
	etl_pipeline=None
	#singleton_logger.sys('test')
	#try:
	if 1:
		
		flags = pipeline_flags.PipelineFlags(singleton_logger)
		environment = Environment(flags, singleton_logger)
		#print singleton_logger.logfile_name()
		#sys.exit(1)
		etl_pipeline = EtlPipeline(flags, environment,singleton_logger)

		etl_logger = etl_pipeline._logger

		etl_pipeline.ExecutePipeline()
		print etl_logger.getElapsedSec()
		if 1:
			while threading.activeCount()>1:
				print '%s: thread pool count = %s' % (etl_logger.getElapsedSec() , threading.activeCount())
				time.sleep(1)
		#print("%s"  %(etl_logger.ins_filename))
		if 0:
			cmd = '/opt/netezzaClient/bin/nzsql  -U ab95022 -W ab95022 -h b4-netezza-01 -p 5480 -d map  -f "%s"' % etl_logger.ins_filename
예제 #29
0
def getenv(name):
    rv = str(Environment.GetEnvironmentVariable(name))
    return rv
예제 #30
0
파일: Gmail.py 프로젝트: soracoder/Apricot
    def onSignInClick(source, rea):
        config = None
        directory = Path.Combine(
            Environment.GetFolderPath(
                Environment.SpecialFolder.ApplicationData),
            Assembly.GetEntryAssembly().GetName().Name)
        backgroundBrush = None
        textColor = SystemColors.ControlTextBrush

        if Directory.Exists(directory):
            fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location)

            for fileName2 in Directory.EnumerateFiles(directory, "*.config"):
                if fileName1.Equals(
                        Path.GetFileNameWithoutExtension(fileName2)):
                    exeConfigurationFileMap = ExeConfigurationFileMap()
                    exeConfigurationFileMap.ExeConfigFilename = fileName2
                    config = ConfigurationManager.OpenMappedExeConfiguration(
                        exeConfigurationFileMap, ConfigurationUserLevel.None)

        if config is None:
            config = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None)
            directory = None

        if config.AppSettings.Settings["BackgroundImage"] is not None:
            fileName = config.AppSettings.Settings[
                "BackgroundImage"].Value if directory is None else Path.Combine(
                    directory,
                    config.AppSettings.Settings["BackgroundImage"].Value)
            fs = None
            bi = BitmapImage()

            try:
                fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.Read)

                bi.BeginInit()
                bi.StreamSource = fs
                bi.CacheOption = BitmapCacheOption.OnLoad
                bi.CreateOptions = BitmapCreateOptions.None
                bi.EndInit()

            finally:
                if fs is not None:
                    fs.Close()

            backgroundBrush = ImageBrush(bi)
            backgroundBrush.TileMode = TileMode.Tile
            backgroundBrush.ViewportUnits = BrushMappingMode.Absolute
            backgroundBrush.Viewport = Rect(0, 0, bi.Width, bi.Height)
            backgroundBrush.Stretch = Stretch.None

            if backgroundBrush.CanFreeze:
                backgroundBrush.Freeze()

        if backgroundBrush is None and config.AppSettings.Settings[
                "BackgroundColor"] is not None:
            if config.AppSettings.Settings["BackgroundColor"].Value.Length > 0:
                backgroundBrush = SolidColorBrush(
                    ColorConverter.ConvertFromString(
                        config.AppSettings.Settings["BackgroundColor"].Value))

                if backgroundBrush.CanFreeze:
                    backgroundBrush.Freeze()

        if config.AppSettings.Settings["TextColor"] is not None:
            if config.AppSettings.Settings["TextColor"].Value.Length > 0:
                textColor = ColorConverter.ConvertFromString(
                    config.AppSettings.Settings["TextColor"].Value)

        textBrush = SolidColorBrush(textColor)

        if textBrush.CanFreeze:
            textBrush.Freeze()

        window = Window()

        def onClick(source, args):
            global username, password

            if not String.IsNullOrEmpty(
                    usernameTextBox.Text) and not String.IsNullOrEmpty(
                        passwordBox.Password):
                username = usernameTextBox.Text
                password = passwordBox.Password

                def onSave():
                    try:
                        fs = None
                        sr = None
                        sw = None

                        try:
                            fs = FileStream(__file__, FileMode.Open,
                                            FileAccess.ReadWrite,
                                            FileShare.Read)
                            encoding = UTF8Encoding(False)
                            sr = StreamReader(fs, encoding, True)
                            lines = Regex.Replace(
                                Regex.Replace(
                                    sr.ReadToEnd(), "username\\s*=\\s*\"\"",
                                    String.Format("username = \"{0}\"",
                                                  username),
                                    RegexOptions.CultureInvariant),
                                "password\\s*=\\s*\"\"",
                                String.Format("password = \"{0}\"", password),
                                RegexOptions.CultureInvariant)
                            fs.SetLength(0)
                            sw = StreamWriter(fs, encoding)
                            sw.Write(lines)

                        finally:
                            if sw is not None:
                                sw.Close()

                            if sr is not None:
                                sr.Close()

                            if fs is not None:
                                fs.Close()

                    except Exception, e:
                        Trace.WriteLine(e.clsException.Message)
                        Trace.WriteLine(e.clsException.StackTrace)

                def onCompleted(task):
                    global menuItem

                    for window in Application.Current.Windows:
                        if window is Application.Current.MainWindow and window.ContextMenu is not None:
                            if window.ContextMenu.Items.Contains(menuItem):
                                window.ContextMenu.Items.Remove(menuItem)
                                window.ContextMenu.Opened -= onOpened

                                if window.ContextMenu.Items[10].GetType(
                                ).IsInstanceOfType(window.ContextMenu.Items[
                                        window.ContextMenu.Items.Count - 4]):
                                    window.ContextMenu.Items.RemoveAt(10)

                    menuItem = None

                Task.Factory.StartNew(
                    onSave, TaskCreationOptions.LongRunning).ContinueWith(
                        onCompleted,
                        TaskScheduler.FromCurrentSynchronizationContext())

            window.Close()
예제 #31
0
* "NLog.dll" is required.
"""

__author__ = "Nishida Takehito <*****@*****.**>"
__version__ = "0.9.0.0"
__date__ = "2018/12/27"

#
# append path.
#
import os
import os.path as path
from sys import path as systemPath
from System import Environment as env

IRONPYTHON_HOME = env.GetEnvironmentVariable("IRONPYTHON_HOME")

if IRONPYTHON_HOME is None:
    raise Exception("Error : Set path of IRONPYTHON_HOME.")

IRONPYTHON_LIB = path.join(IRONPYTHON_HOME, "Lib")
IRONPYTHON_DLLS = path.join(IRONPYTHON_HOME, "DLLs")
IRONPYTHON_NLOG = path.join(IRONPYTHON_HOME, "Lib\\nlog")

_lstPath = []
_lstPath.append(IRONPYTHON_LIB)
_lstPath.append(IRONPYTHON_DLLS)
_lstPath.append(IRONPYTHON_NLOG)

_checkPath = True