Поведение Python отличается в сценарии от командной строки
Когда я набираю "python", чтобы попасть в командную строку python и выполнить этот скрипт, он работает отлично и делает именно то, что мне нужно:
import json
import datetime
dictstr = {'FeedbackScore': '884', 'IDVerified': 'false', 'eBayGoodStanding': 'true', 'AboutMePage': 'false', 'UserSubscription': ['FileExchange'], 'UserIDChanged': 'false', 'PayPalAccountType': 'Business', 'PositiveFeedbackPercent': '100.0', 'Email': 'xxxxxxxxx', 'EIASToken': 'xxxxxxxxxxxxxxx', 'PayPalAccountStatus': 'Active', 'UniquePositiveFeedbackCount': '66', 'UniqueNeutralFeedbackCount': '0', 'SellerInfo': {'CheckoutEnabled': 'true', 'TransactionPercent': '69.0', 'StoreOwner': 'false', 'AllowPaymentEdit': 'false', 'RecoupmentPolicyConsent': None, 'PaymentMethod': 'PayPal', 'GoodStanding': 'true', 'SafePaymentExempt': 'true', 'SellerGuaranteeLevel': 'NotEligible', 'LiveAuctionAuthorized': 'false', 'MerchandizingPref': 'OptIn', 'CIPBankAccountStored': 'false', 'QualifiesForB2BVAT': 'false', 'SchedulingInfo': {'MaxScheduledMinutes': '30240', 'MaxScheduledItems': '3000', 'MinScheduledMinutes': '0'}, 'CharityRegistered': 'false'}, 'UserIDLastChanged': datetime.datetime(2014, 8, 6, 0, 37, 37), 'EnterpriseSeller': 'false', 'Status': 'Confirmed', 'PayPalAccountLevel': 'Verified', 'UserID': 'xxxxxxxxxxxx', 'eBayWikiReadOnly': 'false', 'FeedbackRatingStar': 'Purple', 'UniqueNegativeFeedbackCount': '0', 'VATStatus': 'NoVATTax', 'MotorsDealer': 'false', 'RegistrationDate': datetime.datetime(2003, 1, 12, 0, 21, 42), 'BusinessRole': 'FullMarketPlaceParticipant', 'Site': 'US', 'EBaySubscription': 'FileExchange', 'FeedbackPrivate': 'false', 'NewUser': 'false'}
f = open('json_output.txt','w')
dump_file = json.dumps(dictstr, indent=4, default=str)
f.write(dump_file)
f.close()
Однако, когда я запускаю это как скрипт, содержимое моего выходного файла все в одной строке:
import json
import datetime
import ebaysdk
from ebaysdk.trading import Connection as Trading
def getUser():
api = Trading(config_file='ebay.yaml')
f = open('json_output.txt','w')
api.execute('GetUser', {'UserID': 'xxxxxxxxx'})
dictstr = "%s" % api.response.reply.User
print dictstr
dump_file = json.dumps(dictstr, indent=4, default=str)
f.write(dump_file)
f.close()
if __name__ == "__main__":
getUser()
файл все в одной строке, как оригинальное объявление словаря.
Я использую содержимое stdout в нерабочем примере, чтобы заполнить переменную dictstr в рабочем примере. Я делаю это, потому что я хочу убедиться, что я использую те же самые данные.
Кто-нибудь из вас знает, что я здесь делаю неправильно?
1 ответ
Я рад, что это было так просто.
Исправленный код:
import json
import datetime
import ebaysdk
from ebaysdk.trading import Connection as Trading
def getUser():
api = Trading(config_file='ebay.yaml')
f = open('json_output.txt','w')
api.execute('GetUser', {'UserID': 'xxxxxxxxx'})
dictstr = api.response.dict()
dump_file = json.dumps(dictstr, indent=4, default=str)
f.write(dump_file)
f.close()
if __name__ == "__main__":
getUser()