Python multiple functions with the same decorator execute in main The Next CEO of Stack OverflowWhat 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?

Reshaping json / reparing json inside shell script (remove trailing comma)

Is there a way to save my career from absolute disaster?

Ising model simulation

Physiological effects of huge anime eyes

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

Is it convenient to ask the journal's editor for two additional days to complete a review?

Won the lottery - how do I keep the money?

How do I fit a non linear curve?

How did Beeri the Hittite come up with naming his daughter Yehudit?

What would be the main consequences for a country leaving the WTO?

In the "Harry Potter and the Order of the Phoenix" video game, what potion is used to sabotage Umbridge's speakers?

What is the process for purifying your home if you believe it may have been previously used for pagan worship?

The Ultimate Number Sequence Puzzle

Why did early computer designers eschew integers?

How to use ReplaceAll on an expression that contains a rule

Is a distribution that is normal, but highly skewed, considered Gaussian?

What flight has the highest ratio of timezone difference to flight time?

Calculate the Mean mean of two numbers

Is fine stranded wire ok for main supply line?

Does the Idaho Potato Commission associate potato skins with healthy eating?

Is it correct to say moon starry nights?

Audio Conversion With ADS1243

Is there a reasonable and studied concept of reduction between regular languages?

Raspberry pi 3 B with Ubuntu 18.04 server arm64: what chip



Python multiple functions with the same decorator execute in main



The Next CEO of Stack OverflowWhat 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?










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,08141432




3,08141432










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

        41.3k41743




        41.3k41743





























            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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page