MyDir = os.getcwd().split(os.sep)[-1]
command = re.search(r"(MyDir)", body).group(1)
etc
hi guys,
am trying to have a python script (on windows)
search my outlook email body for certain words using regex
that works fine, coupled with the rest of the script (not shown)
but the minute i want it to search for a variable, ie MyDir it does nothing when i fire off an email to
myself with the word: documents in the body of the email (documents, being the directory the script is located on this occasion; though should populate the variable with whatever top level directory the script is being run from)
now i have read and seen that re.escape is a method to consider, and have copied lots of different variations, and examples
and adapted it to my scenario, but none have worked, i have built the regex as a string also, still no joy
is there anything in my MyDir "variable" that is throwing the regex search off?
am stumped, its my first python script, so am sure am doing something wrong - or maybe i cant use os.getcwd().split(os.sep)[-1] inside regex and have it not look at the variable but the literal string!
thanks for any help, as i have read through similar regex+variable posts on here but havent worked for me
:)
Try:
command = re.search("(" + re.escape(MyDir) + ")", body).group(1)
You searching for the string MyDir not the variable MyDir. You could use str.format
command = re.search(r"({})".format(MyDir), body).group(1)
Related
Im going through the book Dive into Python 3 and in one of its parts theres a .py file which contains a function that has a triple quoted string that as the book explains it, is a document.
When I go into the python shell and import said file and write
print(humansize.approximate_size.__doc__)
it gives me back the said triple quoted string.
I decided Id give it a try myself and created a triple quoted string right under the other one. Saved the file and ran the same code in the python shell - but only the first one appeared. Why is that?
Do i need to install some separate tool to document code ?
Thank you!
I want to access some files in my network drive.
My network drive is called "networkfile". If I just run this on the Window command line, it is working: net use \networkfile\Programs.
However, It didn't work when I put it in the Python script (I'm using Python3). I tried:
a = os.system("net use O:\networkfile\Programs")
a = os.system("net use \networkfile\Programs")
a = os.system("net use \networkfile\Programs")
a = subprocess.run("net use O:\networkfile\Programs", shell=True, stdout=subprocess.PIPE)
None of those work. The error is: "System error 67 has occurred. The network name cannot be found."
Anyone has experienced this before?
Please advice.
Thanks,
your string "net use O:\networkfile\Programs" is being evaluated by the python interpreter as:
net use O:
etworkfile\Programs
because the \n is interpreted as a newline character. You can work around this in a couple different ways
use a raw string (see four paragraphs down here) to prevent backslashes being treated specially (in most cases).
escape the backslashes themselves so they evaluate to a literal backslash (make all "\" into "\\")
use the os.path library to generate the string so the correct directory separator is used regardless of operating system.
Or Should I change my question to 'how to implement regular expression tester like these': regular expression editor python
Maybe this is more like a programming question. My application will read in an article and expose a variable, say TEXT, to represent this article. Allow users to write Python re compatible script to manipulate the TEXT (the article), particularly to replace something.
For example, users could write the following commands, and my app should read it in and execute it:
p = re.compile( 'red')
p.sub( 'color', TEXT)
And I will release my app with something like py2exe, so I think How can I make one python file run another? doesn't work.
I know how to write regular expression, but now "using a Python script to run a Python script" really confuses me.
Do you want to write second word? You need to use input():
word = input('Specify color\n')
U can use just string.replace():
text = 'red'
text.replace('color', word)
If you want to use RegExp:
import re
re.sub('color', word, text)
What is the idomatic/canoncial/best way to get a sibling file (name) in Python 2.7?
That is, if there is file like 'C:\\path\\file.bin' or '/path/file.bin',
how to get 'C:\\path\\anothername.anotherext' or '/path/anothername.anotherext'.
String manipulation, searching for last path separator and replacing the part after that, would of course work, but this seems awfully crude.
In other words, what is idiomatic Python equivalent(s) of these Java snippets:
File sibling = new File(file.getParent(), siblingName);
Or a bit longer for pathname strings:
String siblingPathName = new File(new File(filePathName).getParent(), siblingName).toString();
Note: Java being used above is not relevant to the question.
Note2: If Python 3 has a new way, it would be nice to know that too, even though I'm using Python 2.7 atm.
Use os.path.dirname to get the directory of the file, and then os.path.join to add the sibling's name.
os.path.join(os.path.dirname(f), siblingname)
I'm getting started with using VIM to program Python. I've run into some issues, hopefully someone can help me with this one.
The "gd" command is supposed to take you to the first place a variable is defined/used in the current function. From what I understand, it's the same as doing "[[" to go to the top of the function, then performing a search for the variable name.
Problem is, when I try this in Python functions, vim finds the first occurrence of the variable in the entire file.
Any thoughts on why this happens/how I can fix this?
I think the problem is due to the way that Vim treats a function. From the documentation for [[:
*[[*
[[ [count] sections backward or to the previous '{' in
the first column. |exclusive|
Note that |exclusive-linewise| often applies.
Unless a section is somehow defined specifically for python files somewhere (I'm not convinced this is possible as they're supposed to be two-letter nroff sections), this will assume that there should be an open-brace in the first column, which isn't relevant for python files.
I'd suggest asking on the Vim mailing list to see if there are any plugins or work-arounds for this. Alternatively, you could define a mapping like this:
nmap gd :let varname = '\<<C-R><C-W>\>'<CR>?\<def\><CR>/<C-R>=varname<CR><CR>
This could be done more elegantly with a function, but this was just a quick hack that should work. It maps gd to a function that sets the variable 'varname' to hold the word the cursor is on, searches backward for def and then searches forward for the variable:
:let varname = " Variable setting
'\< " String start and word boundary
<C-R><C-W> " Ctrl-R, Ctrl-W: pull in the word under the cursor
\>' " Word boundary and string end
<CR> " Enter - finish this command
? " Search backwards for...
\<def\> " def but not undefined etc (using word boundaries)
<CR> " Enter - Perform search
/ " Now search forward
<C-R>= " Pull in something from an expression
varname<CR> " The expression is 'varname', so pull in the contents of varname
<CR> " Enter - perform search
I didn't redefine varname in my Vim configuration, and it works good, but I have vim compiled with python.
Maybe this is the problem?
Do you have VIM version 7.x installed, compiled with Python support? To check for this, enter :python print “hello, world”
into VIM. If you see an error message like
E319: Sorry, the command is not available in this version,
then it’s time to get a new one.