Python multiple functions with the same decorator execute in main Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!What is the naming convention in Python for variable and function names?What is the Python equivalent of static variables inside a function?How to return multiple values from a function?What are some common uses for Python decorators?mkdir -p functionality in PythonHow do I detect whether a Python variable is a function?What is a clean, pythonic way to have multiple constructors in Python?How to make a chain of function decorators?How do I get time of a Python program's execution?Why does Python code run faster in a function?

What does this icon in iOS Stardew Valley mean?

Can a non-EU citizen traveling with me come with me through the EU passport line?

What's the meaning of 間時肆拾貳 at a car parking sign

What would be the ideal power source for a cybernetic eye?

Identifying polygons that intersect with another layer using QGIS?

How to run gsettings for another user Ubuntu 18.04.2 LTS

List of Python versions

Sci-Fi book where patients in a coma ward all live in a subconscious world linked together

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

How does debian/ubuntu knows a package has a updated version

Why is my conclusion inconsistent with the van't Hoff equation?

List *all* the tuples!

Using audio cues to encourage good posture

3 doors, three guards, one stone

What does an IRS interview request entail when called in to verify expenses for a sole proprietor small business?

How to answer "Have you ever been terminated?"

How to find out what spells would be useless to a blind NPC spellcaster?

How to deal with a team lead who never gives me credit?

Generate an RGB colour grid

Is it true that "carbohydrates are of no use for the basal metabolic need"?

Apollo command module space walk?

Why are Kinder Surprise Eggs illegal in the USA?

If a contract sometimes uses the wrong name, is it still valid?

Should I use a zero-interest credit card for a large one-time purchase?



Python multiple functions with the same decorator execute in main



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!What is the naming convention in Python for variable and function names?What is the Python equivalent of static variables inside a function?How to return multiple values from a function?What are some common uses for Python decorators?mkdir -p functionality in PythonHow do I detect whether a Python variable is a function?What is a clean, pythonic way to have multiple constructors in Python?How to make a chain of function decorators?How do I get time of a Python program's execution?Why does Python code run faster in a function?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I created a decorator to walk through directories for several functions to do some file operations. Every time when more than one functions with the decorator in the script, only the first one will execute.



import os
import re
import sys


def oswalk_deco(func):
def wrapper(filename, *args):
subdirs = [os.path.abspath(x[0]) for x in os.walk(target_dir)]
subdirs.remove(os.path.abspath(target_dir))
for dir in subdirs:
os.chdir(dir)
for item in os.listdir('.'):
p = re.match(filename, item)
if isinstance(p, re.Match):
match = p.group()
func(match, *args)
return wrapper


def str2uni(string):
if isinstance(string, str):
return string.encode('utf8').decode('unicode_escape')
else:
print('Function "str2uni(string)" only accept strings.')
exit()


@oswalk_deco
def sub_string(filename, regex, substr):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(regex, substr, content)
file.write(content)


@oswalk_deco
def regex_print(filename, string):
with open(filename, 'r') as file:
content = file.read()
relist = re.findall(string, content)

if filename[0] == 'u':
print(str2uni(f'\ufilename[1:-4]'): relist)
elif isinstance(re.match(r'coded2-u.+', filename), re.Match):
print(str2uni(f'\re.search("u[0-9a-z]4,5", filename).group()'): relist)


@oswalk_deco
def docname_format(filename):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(r'docname=".*"', f'docname="filename"', content)
file.write(content)


if __name__ == '__main__':
if len(sys.argv) == 1:
target_dir = '.'
else:
target_dir = sys.argv[1]

regex_print('.*.svg', 'docname=".*"')
regex_print('.*.svg', 'stroke:none')
sub_string('.*.svg', 'docname=".*"', 'docname="stackoverflow.svg')


It seems like I've missed some important properties in Python?










share|improve this question



















  • 2





    for dir in subdirs: os.chdir(dir) looks suspicious to me. If your initial current working directory is "C:", and subdirs is ["foo", "bar"], then in the first iteration chdir(dir) will try to navigate to C:foo. Then in the second iteration, chdir(dir) will try to navigate to C:foobar instead of C:bar. You need to chdir back up to your original current working directory at the end of each iteration.

    – Kevin
    Mar 8 at 17:47












  • ... But unless your program is crashing with a FileNotFoundError, that's probably not the root cause of your problem. Just something to watch out for.

    – Kevin
    Mar 8 at 17:49











  • Thanks for pointing out the mistake! It IS the reason of this problem and nothing to do with the decorators.

    – Elmru
    Mar 8 at 18:07

















1















I created a decorator to walk through directories for several functions to do some file operations. Every time when more than one functions with the decorator in the script, only the first one will execute.



import os
import re
import sys


def oswalk_deco(func):
def wrapper(filename, *args):
subdirs = [os.path.abspath(x[0]) for x in os.walk(target_dir)]
subdirs.remove(os.path.abspath(target_dir))
for dir in subdirs:
os.chdir(dir)
for item in os.listdir('.'):
p = re.match(filename, item)
if isinstance(p, re.Match):
match = p.group()
func(match, *args)
return wrapper


def str2uni(string):
if isinstance(string, str):
return string.encode('utf8').decode('unicode_escape')
else:
print('Function "str2uni(string)" only accept strings.')
exit()


@oswalk_deco
def sub_string(filename, regex, substr):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(regex, substr, content)
file.write(content)


@oswalk_deco
def regex_print(filename, string):
with open(filename, 'r') as file:
content = file.read()
relist = re.findall(string, content)

if filename[0] == 'u':
print(str2uni(f'\ufilename[1:-4]'): relist)
elif isinstance(re.match(r'coded2-u.+', filename), re.Match):
print(str2uni(f'\re.search("u[0-9a-z]4,5", filename).group()'): relist)


@oswalk_deco
def docname_format(filename):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(r'docname=".*"', f'docname="filename"', content)
file.write(content)


if __name__ == '__main__':
if len(sys.argv) == 1:
target_dir = '.'
else:
target_dir = sys.argv[1]

regex_print('.*.svg', 'docname=".*"')
regex_print('.*.svg', 'stroke:none')
sub_string('.*.svg', 'docname=".*"', 'docname="stackoverflow.svg')


It seems like I've missed some important properties in Python?










share|improve this question



















  • 2





    for dir in subdirs: os.chdir(dir) looks suspicious to me. If your initial current working directory is "C:", and subdirs is ["foo", "bar"], then in the first iteration chdir(dir) will try to navigate to C:foo. Then in the second iteration, chdir(dir) will try to navigate to C:foobar instead of C:bar. You need to chdir back up to your original current working directory at the end of each iteration.

    – Kevin
    Mar 8 at 17:47












  • ... But unless your program is crashing with a FileNotFoundError, that's probably not the root cause of your problem. Just something to watch out for.

    – Kevin
    Mar 8 at 17:49











  • Thanks for pointing out the mistake! It IS the reason of this problem and nothing to do with the decorators.

    – Elmru
    Mar 8 at 18:07













1












1








1








I created a decorator to walk through directories for several functions to do some file operations. Every time when more than one functions with the decorator in the script, only the first one will execute.



import os
import re
import sys


def oswalk_deco(func):
def wrapper(filename, *args):
subdirs = [os.path.abspath(x[0]) for x in os.walk(target_dir)]
subdirs.remove(os.path.abspath(target_dir))
for dir in subdirs:
os.chdir(dir)
for item in os.listdir('.'):
p = re.match(filename, item)
if isinstance(p, re.Match):
match = p.group()
func(match, *args)
return wrapper


def str2uni(string):
if isinstance(string, str):
return string.encode('utf8').decode('unicode_escape')
else:
print('Function "str2uni(string)" only accept strings.')
exit()


@oswalk_deco
def sub_string(filename, regex, substr):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(regex, substr, content)
file.write(content)


@oswalk_deco
def regex_print(filename, string):
with open(filename, 'r') as file:
content = file.read()
relist = re.findall(string, content)

if filename[0] == 'u':
print(str2uni(f'\ufilename[1:-4]'): relist)
elif isinstance(re.match(r'coded2-u.+', filename), re.Match):
print(str2uni(f'\re.search("u[0-9a-z]4,5", filename).group()'): relist)


@oswalk_deco
def docname_format(filename):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(r'docname=".*"', f'docname="filename"', content)
file.write(content)


if __name__ == '__main__':
if len(sys.argv) == 1:
target_dir = '.'
else:
target_dir = sys.argv[1]

regex_print('.*.svg', 'docname=".*"')
regex_print('.*.svg', 'stroke:none')
sub_string('.*.svg', 'docname=".*"', 'docname="stackoverflow.svg')


It seems like I've missed some important properties in Python?










share|improve this question
















I created a decorator to walk through directories for several functions to do some file operations. Every time when more than one functions with the decorator in the script, only the first one will execute.



import os
import re
import sys


def oswalk_deco(func):
def wrapper(filename, *args):
subdirs = [os.path.abspath(x[0]) for x in os.walk(target_dir)]
subdirs.remove(os.path.abspath(target_dir))
for dir in subdirs:
os.chdir(dir)
for item in os.listdir('.'):
p = re.match(filename, item)
if isinstance(p, re.Match):
match = p.group()
func(match, *args)
return wrapper


def str2uni(string):
if isinstance(string, str):
return string.encode('utf8').decode('unicode_escape')
else:
print('Function "str2uni(string)" only accept strings.')
exit()


@oswalk_deco
def sub_string(filename, regex, substr):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(regex, substr, content)
file.write(content)


@oswalk_deco
def regex_print(filename, string):
with open(filename, 'r') as file:
content = file.read()
relist = re.findall(string, content)

if filename[0] == 'u':
print(str2uni(f'\ufilename[1:-4]'): relist)
elif isinstance(re.match(r'coded2-u.+', filename), re.Match):
print(str2uni(f'\re.search("u[0-9a-z]4,5", filename).group()'): relist)


@oswalk_deco
def docname_format(filename):
with open(filename, 'r') as file:
content = file.read()
with open(filename, 'w') as file:
content = re.sub(r'docname=".*"', f'docname="filename"', content)
file.write(content)


if __name__ == '__main__':
if len(sys.argv) == 1:
target_dir = '.'
else:
target_dir = sys.argv[1]

regex_print('.*.svg', 'docname=".*"')
regex_print('.*.svg', 'stroke:none')
sub_string('.*.svg', 'docname=".*"', 'docname="stackoverflow.svg')


It seems like I've missed some important properties in Python?







python decorator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 18:17









double-beep

3,13641532




3,13641532










asked Mar 8 at 17:37









ElmruElmru

155




155







  • 2





    for dir in subdirs: os.chdir(dir) looks suspicious to me. If your initial current working directory is "C:", and subdirs is ["foo", "bar"], then in the first iteration chdir(dir) will try to navigate to C:foo. Then in the second iteration, chdir(dir) will try to navigate to C:foobar instead of C:bar. You need to chdir back up to your original current working directory at the end of each iteration.

    – Kevin
    Mar 8 at 17:47












  • ... But unless your program is crashing with a FileNotFoundError, that's probably not the root cause of your problem. Just something to watch out for.

    – Kevin
    Mar 8 at 17:49











  • Thanks for pointing out the mistake! It IS the reason of this problem and nothing to do with the decorators.

    – Elmru
    Mar 8 at 18:07












  • 2





    for dir in subdirs: os.chdir(dir) looks suspicious to me. If your initial current working directory is "C:", and subdirs is ["foo", "bar"], then in the first iteration chdir(dir) will try to navigate to C:foo. Then in the second iteration, chdir(dir) will try to navigate to C:foobar instead of C:bar. You need to chdir back up to your original current working directory at the end of each iteration.

    – Kevin
    Mar 8 at 17:47












  • ... But unless your program is crashing with a FileNotFoundError, that's probably not the root cause of your problem. Just something to watch out for.

    – Kevin
    Mar 8 at 17:49











  • Thanks for pointing out the mistake! It IS the reason of this problem and nothing to do with the decorators.

    – Elmru
    Mar 8 at 18:07







2




2





for dir in subdirs: os.chdir(dir) looks suspicious to me. If your initial current working directory is "C:", and subdirs is ["foo", "bar"], then in the first iteration chdir(dir) will try to navigate to C:foo. Then in the second iteration, chdir(dir) will try to navigate to C:foobar instead of C:bar. You need to chdir back up to your original current working directory at the end of each iteration.

– Kevin
Mar 8 at 17:47






for dir in subdirs: os.chdir(dir) looks suspicious to me. If your initial current working directory is "C:", and subdirs is ["foo", "bar"], then in the first iteration chdir(dir) will try to navigate to C:foo. Then in the second iteration, chdir(dir) will try to navigate to C:foobar instead of C:bar. You need to chdir back up to your original current working directory at the end of each iteration.

– Kevin
Mar 8 at 17:47














... But unless your program is crashing with a FileNotFoundError, that's probably not the root cause of your problem. Just something to watch out for.

– Kevin
Mar 8 at 17:49





... But unless your program is crashing with a FileNotFoundError, that's probably not the root cause of your problem. Just something to watch out for.

– Kevin
Mar 8 at 17:49













Thanks for pointing out the mistake! It IS the reason of this problem and nothing to do with the decorators.

– Elmru
Mar 8 at 18:07





Thanks for pointing out the mistake! It IS the reason of this problem and nothing to do with the decorators.

– Elmru
Mar 8 at 18:07












1 Answer
1






active

oldest

votes


















0














Your target_dir defaults to ., the current working directory, if there's no command line argument given, and in your wrapper function, the os.walk function is always called with target_dir, which, after the os.chdir call, would refer to one of the subfolders of the first call to the decorated function, so os.walk naturally would not be able to find any more subfolders under ., which is already a subfolder.



You can fix this by getting the absolute path of target_dir first:



if len(sys.argv) == 1:
target_dir = '.'
else:
target_dir = sys.argv[1]
target_dir = os.path.abspath(target_dir)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068298%2fpython-multiple-functions-with-the-same-decorator-execute-in-main%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Your target_dir defaults to ., the current working directory, if there's no command line argument given, and in your wrapper function, the os.walk function is always called with target_dir, which, after the os.chdir call, would refer to one of the subfolders of the first call to the decorated function, so os.walk naturally would not be able to find any more subfolders under ., which is already a subfolder.



    You can fix this by getting the absolute path of target_dir first:



    if len(sys.argv) == 1:
    target_dir = '.'
    else:
    target_dir = sys.argv[1]
    target_dir = os.path.abspath(target_dir)





    share|improve this answer



























      0














      Your target_dir defaults to ., the current working directory, if there's no command line argument given, and in your wrapper function, the os.walk function is always called with target_dir, which, after the os.chdir call, would refer to one of the subfolders of the first call to the decorated function, so os.walk naturally would not be able to find any more subfolders under ., which is already a subfolder.



      You can fix this by getting the absolute path of target_dir first:



      if len(sys.argv) == 1:
      target_dir = '.'
      else:
      target_dir = sys.argv[1]
      target_dir = os.path.abspath(target_dir)





      share|improve this answer

























        0












        0








        0







        Your target_dir defaults to ., the current working directory, if there's no command line argument given, and in your wrapper function, the os.walk function is always called with target_dir, which, after the os.chdir call, would refer to one of the subfolders of the first call to the decorated function, so os.walk naturally would not be able to find any more subfolders under ., which is already a subfolder.



        You can fix this by getting the absolute path of target_dir first:



        if len(sys.argv) == 1:
        target_dir = '.'
        else:
        target_dir = sys.argv[1]
        target_dir = os.path.abspath(target_dir)





        share|improve this answer













        Your target_dir defaults to ., the current working directory, if there's no command line argument given, and in your wrapper function, the os.walk function is always called with target_dir, which, after the os.chdir call, would refer to one of the subfolders of the first call to the decorated function, so os.walk naturally would not be able to find any more subfolders under ., which is already a subfolder.



        You can fix this by getting the absolute path of target_dir first:



        if len(sys.argv) == 1:
        target_dir = '.'
        else:
        target_dir = sys.argv[1]
        target_dir = os.path.abspath(target_dir)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 18:07









        blhsingblhsing

        44.3k51745




        44.3k51745





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068298%2fpython-multiple-functions-with-the-same-decorator-execute-in-main%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved