Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在脚本';之外时在终端中执行Python脚本;s目录_Python_Python 3.x - Fatal编程技术网

在脚本';之外时在终端中执行Python脚本;s目录

在脚本';之外时在终端中执行Python脚本;s目录,python,python-3.x,Python,Python 3.x,我有一个Python脚本,可以提示输入文本,搜索在线韩语词典,然后下载MP3音频文件查找找到的单词。我使用脚本帮助我制作带有音频的Anki抽认卡。脚本最初来自于 我可以在保存脚本的目录中从终端执行脚本。但是,当我在另一个目录中并通过调用脚本的完整路径来执行脚本时,脚本似乎正在运行,但找不到任何单词或下载任何MP3。当我从不同的目录调用脚本时,我无法理解为什么脚本无法正确执行 脚本存储在我的Mac电脑的下载文件夹中/Users/matt/downloads 因此,当我运行以下命令时,它可以工作:

我有一个Python脚本,可以提示输入文本,搜索在线韩语词典,然后下载MP3音频文件查找找到的单词。我使用脚本帮助我制作带有音频的Anki抽认卡。脚本最初来自于

我可以在保存脚本的目录中从终端执行脚本。但是,当我在另一个目录中并通过调用脚本的完整路径来执行脚本时,脚本似乎正在运行,但找不到任何单词或下载任何MP3。当我从不同的目录调用脚本时,我无法理解为什么脚本无法正确执行

脚本存储在我的Mac电脑的下载文件夹中
/Users/matt/downloads
因此,当我运行以下命令时,它可以工作:

cd Downloads
python3 naver.py
但是,当我运行以下命令时,脚本会执行,但不会下载任何MP3:

python3 /Users/matt/Downloads/naver.py
完整的Python脚本如下所示:

import urllib.request, json, codecs, math, time
 
def searchWords(koreanWords):
    url = ('https://ko.dict.naver.com/api3/koko/search?' + urllib.parse.urlencode({'query': koreanWords}) + '&range=word&page=1')
    response = urllib.request.urlopen(url)
    reader = codecs.getreader("utf-8")
    jsonInfo = json.load(reader(response))
    pageCount = jsonInfo["pagerInfo"]["totalPages"]
    searchData = jsonInfo["searchResultMap"]["searchResultListMap"]["WORD"]["items"]
 
    for pageCountInc in range(0, pageCount):
        if pageCountInc != 0:
            url = ('https://ko.dict.naver.com/api3/koko/search?' + urllib.parse.urlencode({'query': koreanWords}) + '&range=word&page=' + str(pageCountInc+1))
        response = urllib.request.urlopen(url)
        reader = codecs.getreader("utf-8")
        jsonInfo = json.load(reader(response))
        searchData = jsonInfo["searchResultMap"]["searchResultListMap"]["WORD"]["items"]
        for z in range (0, len(searchData)):
            if searchData[z]["handleEntry"] in unchangedWordList:
                if searchData[z]["searchPhoneticSymbolList"]:
                    if searchData[z]["searchPhoneticSymbolList"][0]["phoneticSymbolPath"] != "":
                        timesDownloaded[unchangedWordList.index(searchData[z]["handleEntry"])] += 1
                        mp3Link = searchData[z]["searchPhoneticSymbolList"][0]["phoneticSymbolPath"]
                        if mp3Link not in mp3Links:
                            mp3Links.append(mp3Link)
                            urllib.request.urlretrieve(mp3Link, searchData[z]["handleEntry"] + str(timesDownloaded[unchangedWordList.index(searchData[z]["handleEntry"])]) + ".mp3")
                            time.sleep(.3)
   
def parseWords(listOfWords):
    for x in range(0, math.floor(len(listOfWords)/10)):
        tempWords = []
        for y in range(0, 10):
            tempWords.append(listOfWords[x*10+y])
 
        print("Searching: " + str(x+1) + "/" + str(math.ceil(len(listOfWords)/10)))
        searchWords(tempWords)
 
    tempWords = []
    for y in range(math.floor(len(listOfWords)/10)*10+1, len(listOfWords)):
        tempWords.append(listOfWords[y])
    print("Searching: " + str((math.ceil(len(listOfWords)/10))) + "/" + str(math.ceil(len(listOfWords)/10)))
    searchWords(tempWords)
unfoundWords = []
unchangedWordList = []
timesDownloaded = []
mp3Links = []
wordInputs = unchangedWordList = input('Enter Words: ').split()
timesDownloaded = [0] * len(unchangedWordList)
 
parseWords(wordInputs)
 
for z in range(0, len(timesDownloaded)):
    if(timesDownloaded[z] == 0):
        unfoundWords.append(unchangedWordList[z])
 
if unfoundWords:
    print(",".join(str(x) for x in unfoundWords) + " could not be found.")
    print("Rerunning individual searches for unfound words.")
    print(unfoundWords)
    oldUnfoundWords = unfoundWords
    unfoundWords = []
    for x in range(0, len(oldUnfoundWords)):
        print("Searching: " + str(x+1) + "/" + str(len(oldUnfoundWords)))
        searchWords(oldUnfoundWords[x])
 
    for z in range(0, len(timesDownloaded)):
        if(timesDownloaded[z] == 0):
            unfoundWords.append(unchangedWordList[z])
 
    if unfoundWords:
        print(",".join(str(x) for x in unfoundWords) + " could not be found.")

原因如下:
python文件在当前目录中运行。因此,当您运行以下命令时:
python3/Users/matt/Downloads/naver.py
,它要么在当前目录中运行并保存mp3文件,要么根本不保存任何内容,如果它没有保存的权限。

要回答如何保存到特定文件夹的问题,请使用pathlib构建到mp3文件夹的路径

import os
from pathlib import Path
# Create parent folder
mp3DIR = os.path.join(Path.home(),'Music')
basename = searchData[z]["handleEntry"] 
           + str(timesDownloaded[unchangedWordList.index(searchData[z]["handleEntry"])]) + ".mp3"
urllib.request.urlretrieve(mp3Link, os.path.join(mp3Dir, basename))

如何将MP3文件设置为保存到特定目录而不是当前目录?