簡體   English   中英

我無法使用 python.exe 運行 python 程序

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

我有一個 python 程序,它應該從名為“Notes”的文件夾中打開一個隨機文件。 為此,我正在使用模塊“os”。 當我在 IDLE 中打開腳本並運行它時,它運行良好,但是當我嘗試使用 python.exe 運行它時,它不起作用。 window 會暫時打開然后消失,但文件不會打開。 這是代碼:

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])

文件 D.txt 列出了我 D 盤中所有文件的路徑。 整個 python 文件夾安裝在驅動器 D 中,而不是通常的安裝位置。

很有可能,它正在運行並立即關閉。 嘗試在程序末尾添加time.sleep(99) ,然后看看會發生什么。

如果添加 time.sleep 不起作用,請打開終端並 cd 進入目錄。 運行python3 yourfile.py 如果有錯誤,它應該出現在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM