如何在Windows10中从bash提示符运行python'__main__'程序文件?

时间:2018-07-05 19:34:40

标签: python python-3.x git-bash

我正在尝试运行python3程序文件,并且出现了一些意外行为。

我将首先使用PATH和环境设置配置开始。当我跑步时:

which Python

我得到:

/c/Program Files/Python36/python

从那里,我cd进入python程序所在的目录以准备运行该程序。

粗略地说,这就是我的python程序的设置方式:

import modulesNeeded

print('1st debug statement to show program execution')

# variables declared as needed

def aFunctionNeeded():
    print('2nd debug statement to show fxn exe, never prints')
    ... function logic...

if __name__ == '__main__':
    aFunctionNeeded() # Never gets called

这里是带有我正在使用的代码的存储库的链接,以防您需要有关实现的更多详细信息。请记住,API密钥未发布,但API密钥正确在本地文件中:

https://github.com/lopezdp/API.Mashups

我的问题围绕着为什么文件中的第一条调试语句打印到终端,而不是函数中的第二条调试语句打印到终端?

findRestaurant.py文件和geocode.py文件中都发生这种情况。

我知道我已经正确编写了if __name__ == '__main__':程序入口点,因为这与我对其他程序所做的操作完全相同,但是在这种情况下,我可能会丢失一些我没有注意到的东西。

如果这是我在bash终端中运行程序时的输出:

$ python findRestaurant.py
inside geo
inside find

然后,为什么看来没有从 main 调用我的伪代码中显示的aFunctionNeeded()方法?

为什么在第一个调试语句打印到终端后,两个程序似乎都立即失败?

findRestaurant.py文件,也可以在上面的链接中找到

from geocode import getGeocodeLocation
import json
import httplib2

import sys
import codecs

print('inside find')

sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

foursquare_client_id = "..."
foursquare_client_secret = "..."


def findARestaurant(mealType,location):
    print('inside findFxn')
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    latitude, longitude = getGeocodeLocation(location)
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])

    if result['response']['venues']:
        #3.  Grab the first restaurant
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id']
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        address = ""
        for i in restaurant_address:
            address += i + " "
        restaurant_address = address
        #4.  Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
        url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
        result = json.loads(h.request(url, 'GET')[1])
        #5.  Grab the first image
        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            #6.  if no image available, insert default image url
            imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
        #7.  return a dictionary containing the restaurant name, address, and image url
        restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
        print ("Restaurant Name: %s" % restaurantInfo['name'])
        print ("Restaurant Address: %s" % restaurantInfo['address'])
        print ("Image: %s \n" % restaurantInfo['image'])
        return restaurantInfo
    else:
        print ("No Restaurants Found for %s" % location)
        return "No Restaurants Found"

if __name__ == '__main__':
    findARestaurant("Pizza", "Tokyo, Japan")

geocode.py文件,也可以在上面的链接中找到

import httplib2
import json

print('inside geo')

def getGeocodeLocation(inputString):
    print('inside of geoFxn')
    # Use Google Maps to convert a location into Latitute/Longitute coordinates
    # FORMAT: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY
    google_api_key = "..."
    locationString = inputString.replace(" ", "+")
    url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s' % (locationString, google_api_key))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])
    latitude = result['results'][0]['geometry']['location']['lat']
    longitude = result['results'][0]['geometry']['location']['lng']
    return (latitude,longitude)

1 个答案:

答案 0 :(得分:3)

之所以看不到代码后半部分的输出,是因为您已经用这些行反弹了标准输出和错误流:

sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

我不确定这些行为什么会破坏您的工作,也许您的控制台不希望使用utf8编码的输出...但是由于它们无法按预期运行,因此您看不到任何内容因为您将stderr流与stdout流一起反弹了,所以从其余代码(包括错误消息)中删除了。