简体   繁体   中英

Script working with os.path but not with pathlib (SIGTRAP)

I was advised to take advantage of the pathlib module in Python 3.6, as I am designing a script on Linux that'll be used in production on Windows machines.

pathlib does seem promising, but while my code with the os module works great:

class Watcher:
    DIRECTORY_TO_WATCH = os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs')

    print(DIRECTORY_TO_WATCH)

    def __init__(self):
        self.observer = Observer()


    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()

If I change to the pathlib equivalent:

from pathlib import Path as p

class Watcher:
    DIRECTORY_TO_WATCH = p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/')
    print(DIRECTORY_TO_WATCH)

    def __init__(self):
        self.observer = Observer()


    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False)
        self.observer.start()

80% I'll get this error in Pycharm:

Process finished with exit code 133 (interrupted by signal 5: SIGTRAP)

or the script will run, but my triggers won't fire at all. Confusing.

Ok. I've found the solution:

os.path.join(os.path.expanduser("~"), 'Dropbox', 'credits_hd_jobs')

returns an str , while:

p.joinpath(p.home(), 'Dropbox', 'credits_hd_jobs/')

returns a PosixPath

I ended up casting the latter as a string by using str() , although this looks ugly to me. I'm keeping the question open for better answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM