Printing Parameter Values returning Unexpected Result, Python - python

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.

Related

remove shell escape characters from a string

I am creating a terminal based python application whereby the user drags and drops a csv file into the terminal to get the file path. The file path is therefore escaped.
How do I remove all instances of this?
For example, I have a file
thisisatestfile/\(2).csv
but when I drag it into terminal it appears as:
thisisatestfile\:\\\(2\).csv
I have a list of all the shell escape characters that I need to remove:
link to characters
I am not very good at regex so any help much appreciated!
I just implemented this with shlex.split
>>> shlex.split('thisisatestfile/\(2).csv')
['thisisatestfile/(2).csv']
Since this method is intended for taking a raw shell invocation and returning a list of args to be passed to, e.g., subprocess.Popen, it returns a list. If you know you only have a single string to process, just grab the first element of the returned list.
>>> shlex.split('thisisatestfile/\(2).csv')[0]
'thisisatestfile/(2).csv'

Getting (and appending) correct file path in Python 2.7

I have a previously defined file name in a string format, and a previously defined variable called value. I am trying to store a variable that looks like:
C:\Users\Me\Desktop\Value_Validation_Report
with the syntax below, I instead get:
C:\Users\Me\Desktop\Value\ _Validation_Report
target_dir= os.path.dirname(os.path.realpath(FileName))
ValidationReport=os.path.join(target_dir,value,"_Validation_Report")
print ValidationReport
Every other combination I have tried leads to an error. Any help would be greatly appreciated!
If value is a String, you must concatenate that with "_Validation_Report
target_dir= os.path.dirname(os.path.realpath(FileName))
ValidationReport=os.path.join(target_dir,value + "_Validation_Report")
print ValidationReport
os.path.join will add a separator (which depends on the operating system) between each string you give it. To avoid this, simply put your value and "_Validation_Report" strings together as one String. See more about os.path.join.

Running PHP script using python

I'm trying to run this script using the code
subprocess.call(["php C:\Python27\a.php"])
and I'm getting this error:
FileNotFoundError: [WinError 2] The system cannot find the file specified
i have tried changing path but nothing seems to work, any ideas?
Either
subprocess.call(["php", "C:\\Python27\\a.php"])
or
subprocess.call(["php", r"C:\Python27\a.php"])
should work.
Try this:
subprocess.call(["php", "C:\\Python27\\a.php"])
From the documentation:
args is required for all calls and should be a string, or a sequence
of program arguments. Providing a sequence of arguments is generally
preferred, as it allows the module to take care of any required
escaping and quoting of arguments (e.g. to permit spaces in file
names). If passing a single string, either shell must be True (see
below) or else the string must simply name the program to be executed
without specifying any arguments.
Also note that in python, like many other languages, the backslash in a normal string has special meaning. You'll have to use double backslashes or a raw string to get the behavior you want.

Convert a dynamically generated string to raw text

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)

Python -- Quotations around filenames

I'm not quite sure when I need to put quotations around the filenames in Python.
For example, when I set
f = open(file)
I can run something like
len(f.read())
and it will run fine.
However, when I do it directly, it only works with
len(open("file").read())
Likewise, in terminal when running from Python I always have to use quotations.
What is the 'rule' when using quotations?
Thank you.
In python you can always use the name of a variable or function outside quotations, but the name of a file is usually not a variable.
If file is the name of a string variable you can always do open(file).read(), however if it is literally the filename you must always do open("file").read().
Quotations indicate a string literal constant. No quotations indicate that you're referencing a variable, which may itself be a string (in this case, populated with the path to a file).

Categories

Resources