我如何 运行 python '__main__' 来自 bash 提示符的程序文件 Windows10?
How do I run python '__main__' program file from bash prompt in Windows10?
我正在尝试 运行 一个 python3 程序文件,但出现了一些意外行为。
我将首先从我的 PATH 和 env 设置配置开始。当我 运行:
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
这是一个 link 存储库,其中包含我正在使用的代码,以防您需要有关实现的更多详细信息。请记住 API 密钥未发布,但 API 密钥在本地文件中正确:
https://github.com/lopezdp/API.Mashups
我的问题围绕着为什么我的文件中的第一个调试语句打印到终端,而不是函数中的第二个调试语句?
这在 findRestaurant.py
文件和 geocode.py
文件中都发生了。
我知道我已经正确地编写了我的 if __name__ == '__main__':
程序入口点,因为这与我为其他程序所做的完全相同,但在这种情况下,我可能会遗漏一些我没有注意到的东西。
如果这是我在 bash 终端中 运行 我的程序时的输出:
$ python findRestaurant.py
inside geo
inside find
那么,为什么我的伪代码中显示的 aFunctionNeeded()
方法似乎没有从 main 调用?
为什么两个程序似乎在第一个调试语句打印到终端后立即失败?
findRestaurant.py 上面link中也可以找到的文件
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上面link中也可以找到的文件
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)
您没有看到代码后面部分的输出的原因是您用这些行重新启动了标准输出和错误流:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
我不太确定为什么这些行会破坏你的东西,也许你的控制台不期望 utf8
编码输出...但是因为它们没有按预期工作,你不是从您的其余代码中看到任何内容,包括错误消息,因为您将 stderr
流与 stdout
流一起反弹。
我正在尝试 运行 一个 python3 程序文件,但出现了一些意外行为。
我将首先从我的 PATH 和 env 设置配置开始。当我 运行:
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
这是一个 link 存储库,其中包含我正在使用的代码,以防您需要有关实现的更多详细信息。请记住 API 密钥未发布,但 API 密钥在本地文件中正确:
https://github.com/lopezdp/API.Mashups
我的问题围绕着为什么我的文件中的第一个调试语句打印到终端,而不是函数中的第二个调试语句?
这在 findRestaurant.py
文件和 geocode.py
文件中都发生了。
我知道我已经正确地编写了我的 if __name__ == '__main__':
程序入口点,因为这与我为其他程序所做的完全相同,但在这种情况下,我可能会遗漏一些我没有注意到的东西。
如果这是我在 bash 终端中 运行 我的程序时的输出:
$ python findRestaurant.py
inside geo
inside find
那么,为什么我的伪代码中显示的 aFunctionNeeded()
方法似乎没有从 main 调用?
为什么两个程序似乎在第一个调试语句打印到终端后立即失败?
findRestaurant.py 上面link中也可以找到的文件
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上面link中也可以找到的文件
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)
您没有看到代码后面部分的输出的原因是您用这些行重新启动了标准输出和错误流:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
我不太确定为什么这些行会破坏你的东西,也许你的控制台不期望 utf8
编码输出...但是因为它们没有按预期工作,你不是从您的其余代码中看到任何内容,包括错误消息,因为您将 stderr
流与 stdout
流一起反弹。