'I'm unable to run a python program using python.exe

I have a python program that is supposed to open a random file from a folder named 'Notes'. For that I'm using the module 'os'. When I open the script in IDLE and run it it works perfectly but when I try to run it with python.exe it doesn't work. A window opens momentarily and then disappears but the file doesn't open. Here is the code:

import os
from random import randint
def search_string_in_file(file_name, string_to_search):
    """Search for the given string in file and return lines containing that string,
    along with line numbers"""
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            line_number += 1
            if string_to_search in line:
                # If yes, then add the line number & line as a tuple in the list
                list_of_results.append((line_number,line.rstrip()))
    # Return list of tuples containing line numbers and lines where string is found
    return list_of_results

matched_lines = search_string_in_file('D:/D.txt', 'Notes')
y = randint(1,len(matched_lines))
os.startfile(matched_lines[y][1])

The file D.txt has a list of paths of all files in my D drive. The entire python folder is installed in drive D rather than its usual install location.



Solution 1:[1]

Chances are, it's running and immediately closing. Try adding time.sleep(99) at the end of your program, and see what happens then.

If adding time.sleep does not work, open the terminal and cd into the directory. Run python3 yourfile.py. If there is an error, it should appear here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1