Home > Net >  I Can use python in cmd but not in python.exe?
I Can use python in cmd but not in python.exe?

Time:12-05

I can use cmd to run python, But I cannot use python.exe directly. I have already built python environment,but when I turn on a python file,the program just crashes.

python version:
3.10

path:
C:\users\user\appdata\local\programs\python\pyhon310\python.exe

the code showed below

import requests
import json
import pandas as pd


url = requests.get(r'https://shopee.tw/api/v4/search/search_items?by=pop&limit=100&match_id=1778234&newest=0&order=desc&page_type=shop')
data = json.loads(url.text)
items_count = int(data['total_count'])

output = list()

for page in range(0, items_count, 100):


    url = requests.get(f'https://shopee.tw/api/v4/search/search_items?by=pop&limit=100&match_id=1778234&newest={page}&order=desc&page_type=shop')

    data = json.loads(url.text)

    for item in data['items']:
        
        item_name = item['item_basic']['name']

        
        item_price = str(item['item_basic']['price'])[:-5]
        
        item_historical_sold = item['item_basic']['historical_sold']
        
        item_view_count = item['item_basic']['view_count']
        
        print(f'{item_name}:{item_price}:{item_historical_sold}:{item_view_count}')
        # 把資料寫入列表
        output.append([item_name, item_price, item_historical_sold, item_view_count])
df = pd.DataFrame(output, columns=['商品名稱', '價格', '已售出', '瀏覽數'])
df.to_excel('列表JSON版12041301.xlsx', index=False)

input('Enter the any press to exit')

CodePudding user response:

Windows is not very friendly for double-clicking on console programs. It will run the program in a temporary console, which will disappear after it finishes. You have tried to remedy this with your input statement at the end, which is a good thing to do. However, this only works if your program runs without errors. When you get an exception, this statement will never execute, and the console will disappear before you get a chance to read the error messages.

So I suggest to catch the possible exceptions and print them before the input statement. One possible exception that I could see, is when this script is run in a working directory where you have no write access.

Try this and see if there is an error message.

import requests
import json
import pandas as pd
import traceback

def main():
    # Your original code, intended 4 spaces
    url = requests.get(r'https://shopee.tw/api/v4/search/search_items?by=pop&limit=100&match_id=1778234&newest=0&order=desc&page_type=shop')
.... etc....
    df.to_excel('列表JSON版12041301.xlsx', index=False)

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        traceback.print_exc()
    input('Press ENTER key to exit')
  • Related