I'm having difficulty with different string arrays. Previously, there were string arrays only in properties files. Currently, the system has string arrays in properties files and set as environmental variables in the user's .bashrc file. The string arrays look like the following in both the properties and .bashrc files.
STRING_ARRAY="host1","host2","host3"
Previously, there was a simple pair of for loops that read a series of these string arrays and passed them into some function.
for k in ("STRING_ARRAY","SOME_OTHER_ARRAY"):
globals()[k] = globals()[k].replace("\"",'').split(",")
for stringarray,otherarray in zip(STRING_ARRAY, SOME_OTHER_ARRAY):
someFunction(stringarray,otherarray)
This worked fine. The problem arose when some of the variables were moved out of properties files that were passed into the python script and into environmental variables. It seems that when using either os.getenv("HOSTSTRINGARRAY") or os.environ["HOSTSTRINGARRAY"], the os library returns the array of strings without the accompanying quotation marks so
PROPERTIES_STRING_ARRAY="host1","host2","host3"
print PROPERTIES_STRING_ARRAY
returns
"host1","host2","host3"
whereas
ENV_VAR_STRING_ARRAY="host1","host2","host3"
print os.getenv("ENV_VAR_STRING_ARRAY")
returns
host1,host2,host3
This is a problem because I can't seem to mix and match the two types of variables as follows
for k in ("POPERTIES_STRING_ARRAY",os.getenv("ENV_VAR_OTHER_ARRAY")):
globals()[k] = globals()[k].replace("\"",'').split(",")
for stringarray,otherarray in zip(STRING_ARRAY, os.getenv("ENV_VAR_OTHER_ARRAY")):
someFunction(stringarray,otherarray)
So my question is, how do get os.getenv or os.environ to return a comma separated list of strings without stripping off the quotations marks enclosing the individual strings?
Use ' single quote to declare the string. It should work now.
ENV_VAR_STRING_ARRAY='"host1","host2","host3"'
Related
I'm working to create a tuple in Python in the following way:
tuple = (the_schema['fields'][i]['name'],the_schema['fields'][i]['type'])
and am getting the output ('stn', 'str').
My desired output is ('stn', str), where the second element of the tuple doesn't have the single quotes.
When I print (the_schema['fields'][i]['type']), I get str as desired. The issue, as I understand, is that Python automatically formats the tuple with quotations. How can I remove the quotation? I have tried the .replace() and .strip() methods, as well as something similar to ",".join([str(s) for s in list(k)]).
From python 3.6 on, you can use f-strings to create strings using variables, and that is quite easy to do.
Here, for your output you could use:
string_tuple = f"('{the_schema['fields'][i]['name']}', {the_schema['fields'][i]['type']})"
I was wondering if there was a way to read a string literal stored in a variable. I was essentially trying to extract the file name for a variable containing a file path. I'm aware that you need to place r' before the path name. In my example below, the variable I'm trying to update is 'test'. So basically I'm unaware of how I can use r' on the variable name to avoid parts of the path being read as unicode characters. Is there a way to do this?
test='NAI\site_summaries\410_-_407_Central'
head,tail=os.path.split(test)
print(tail)
The code above returns 'site_summaries_-_407_Central', where it should be returning '410_-_407_Central'. Please keep in mind that I have a variable containing a list of these paths but I just chose to show one path for the sake of simplicity.
I have the following python script snidbit:
inLines = sys.argv[0]
arcpy.AddMessage(inLines)
The input parameter is a multivalue input whereby the user can navigate to a file locations and choose multiple files as the input.
When I print out the variable, I get the follwoing:
Y:\2012_data\INFRASTRUCTURE.gdb\Buildings;'Z:\DATA FOR
2009\Base.gdb\CREEKS_UTM';'Z:\DATA FOR 2009\Base.gdb\LAKES_UTM'
Notice on the Z:drive, it is returning the path with single quotes around it, whereas the Y:drive does not. I believe this is caused by the spaces in the Z:drive paths. Is there a way to force the Z:drive paths to return without the quotes?
Thanks,
Mike
I managed to solve this issue. Python handles the parameters differently because of the path names. In the first parameter, there are no spaces in the file path. In the other 2 parameters, there are spaces. Python doesn't like spaces, so it forces the file path into a string value. I just wrote some code to override this.
I have a list of strings and a command I'd like to run with Popen. The command takes the strings as input arguments.
How can I easily add the entire list...
list=['asdf','qwer','zxcv',...]
...as comma separated input shown below:
Popen(['cmd','asdf','qwer','zxcv',...])
I won't be able to do this because it won't convert list to str implicitly:
Popen(['cmd',list])
Nor this, because it simply won't allow for spaces within a string:
Popen(['cmd',' '.join(list)])
Is there an alternative?
I do not want to use the 'shell=True' option.
You can do the following to create a new list from two (or more) separate lists.
['cmd'] + list
This creates a new list for you with the contents of both. As you mentioned, the syntax looks and does exactly as you expect, which is adding two lists together.
Note: I would also like to warn that you shouldn't use list as a variable name. Since this means you are shadowing the built-in list type. Which could cause unforeseen problems later.
I am quite new to python and i struck an issue wherein, I am dynamically retrieving a string from a dictionary which looks like this
files="eputilities/epbalancing_alb/referenced assemblies/model/cv6_xmltypemodel_xp2.cs"
I am unable to to perform any actions on this particular file as it is reading the path as 2 different strings
eputilities/epbalancing_alb/referenced and assemblies/model/cv6_xmltypemodel_xp2.cs
as there is a space between referenced and assemblies.
I wanted to know how to convert this to raw_string (ignore the space, but still keep the space between the two and consider it as one string)
I'm not able to figure this out although several comments where there on the web.
Please do help.
Thanks
From the comments to the other answer, I understand that you want to execute some external tool and pass a parameter (a filename) to it. This parameter, however, has spaces in it.
I'd propose to approaches; definitely, I'd use subprocess, not os.system.
import subprocess
# Option 1
subprocess.call([path_to_executable, parameter])
# Option 2
subprocess.call("%s \"%s\"" % (path_to_executable, parameter), shell=True)
For me, both worked, please check if they work yor you as well.
Explanations:
Option 1 takes a list of strings, where the first string has to be the path to the executable and all others are interpreted as command line arguments. As subprocess.call knows about each of these entities, it properly calls the external so that it understand thatparameter` is to be interpreted as one string with spaces - and not as two or more parameters.
Option 2 is different. With the keyword-argument shell=True we tell subprocess.call to execute the call through a shell, i.e., the first positional argument is "interpreted as if it was typed like this in a shell". But now, we have to prepare this string accordingly. So what would you do if you had to type a filename with spaces as a parameter? You'd put it between double quotes. This is what I do here.
Standard string building in python works like this
'%s foo %s'%(str_val_1, str_val_2)
So if I'm understanding you right either have a list of two strings or two different string variables.
For the prior do this:
' '.join(list)
For the latter do this:
'%s %s'%(string_1, string_2)