Search code examples
pythonfunctionyoutube-dl

Python script calling function before first function


So, I'm working on a personal project. I made two python scripts using youtube-dl to download a song and a thumbnail, respectively. The script for the song downloads the song as an .mp3 file with a custom name (designated by an argument). The script for the thumbnail downloads the .webp file of the thumbnail with a custom name (designated by an argument) and converts it to png and then jpg. I put these two into functions and in different folders, like this.

yt2mp3 -- youtubeMP3.py
          __main__.py
          thumbnails.py -- __main__.py
                           downloadimg.py

The full scripts can be found at this github repo: https://github.com/ignition-ctrl/yt2mp3
The code is not pretty but it works. However, the issue is this. I have a function in my .bashrc called downloadmusic(). It'll take two arguments, the link and the custom filename and run the python script youtubeMP3.py with the arguments. The youtubeMP3.py has the function download_music() and within that function it has a reference to the function download_thumbnail from downloadimg.py. My problem is that from my terminal, I can see that it runs download_thumbnail twice. Once when starting the script, and then after running download_music(). I only want it to run after download_music(). The code is supposed to only run in this code.

determiner = input("Do you want to download the thumbnail?")
    if determiner == "yes" or "y" or "Yes":
        downloadimg.download_thumbnail(str(ytname), str(filename))
    else:
        exit(0)

That's the only reference to the download_thumbnail, but I can see the terminal output from download_thumbnail() before the print statements I put in download_music(). I also get two copies of the jpg file that comes from download_thumbnail(). I've been scratching my head about this all day. If anyone could help, I'd appreciate it.


Solution

  • First time download_thumbnail() is called when you import the module. It tries to run

    try:
        download_thumbnail(sys.argv[1], sys.argv[2])
    except IndexError:
        raise NameError("Please provide a link and your desired filename")
    

    you can wrap this inside an if statement like this

    if __name__ == '__main__':
        try:
            download_thumbnail(sys.argv[1], sys.argv[2])
        except IndexError:
            raise NameError("Please provide a link and your desired filename")try:
        download_thumbnail(sys.argv[1], sys.argv[2])
    
    

    so that this block will run only when the file is executed directly, not when importing.