Browse Source

add tempname() function to grass.script.core, fix https://trac.osgeo.org/grass/ticket/3615

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@73205 15284696-431f-4ddb-bdfa-cd5b030d7da7
Stefan Blumentrath 6 years ago
parent
commit
81e9ff7ad0
1 changed files with 26 additions and 0 deletions
  1. 26 0
      lib/python/script/core.py

+ 26 - 0
lib/python/script/core.py

@@ -25,6 +25,8 @@ import atexit
 import subprocess
 import subprocess
 import shutil
 import shutil
 import codecs
 import codecs
+import string
+import random
 import types as python_types
 import types as python_types
 
 
 from .utils import KeyValue, parse_key_val, basename, encode
 from .utils import KeyValue, parse_key_val, basename, encode
@@ -822,6 +824,30 @@ def tempdir():
     return tmp
     return tmp
 
 
 
 
+def tempname(length, lowercase=False):
+    """Generate a GRASS and SQL compliant random name starting with tmp_
+    followed by a random part of length "length"
+
+    :param int length: length of the random part of the name to generate
+    :param bool lowercase: use only lowercase characters to generate name
+    :returns: String with a random name of length "length" starting with a letter
+    :rtype: str
+
+    :Example:
+
+    >>> tempname(12)
+    'tmp_MxMa1kAS13s9'
+    """
+
+    chars = string.ascii_lowercase + string.digits
+    if not lowercase:
+        chars += string.ascii_uppercase
+    random_part = ''.join(random.choice(chars) for _ in range(length))
+    randomname = 'tmp_' + random_part
+
+    return randomname
+
+
 def _compare_projection(dic):
 def _compare_projection(dic):
     """Check if projection has some possibility of duplicate names like
     """Check if projection has some possibility of duplicate names like
     Universal Transverse Mercator and Universe Transverse Mercator and
     Universal Transverse Mercator and Universe Transverse Mercator and