2

This is a very weried situation, in vscode, I edited my code in the root directory and saved it as test_distribution.py. After I run this file in vscode terminal. Everytime I edit and save this file, it gets run automatically.

So I moved this file to the subfolder of this project, but I found out it still get run when I edit and save this file. So I changed the file name to distribution_test.py and add logging and save this file again. It turns out it will still run when I edit and save this file.

How should I figure out why this is happening? What kind of info should I log out in order to figure out this issue?

As you can see the 1300000_bake.xlsx is generated by this python file, I even moved this python file to a different folder and changed the name of it as I stated above, I am very curious how to find out which program is running this

Pics as follow:

for store_id in store_ids:
df = pd.DataFrame(columns=columns)
for query_date in date_range:
    logging.info(f"提高计算速度, 使用常规kind_code_cate1类型")
    kind_cate1s = normal_cate1
    for kind_cate1 in kind_cate1s:
        for setting in [dev_setting, prod_setting]:
            eng = conn(setting)
            delivery_cycle = pd.read_sql(
                f"select delivery_cycle from dim_mty_goods where kind_code_cate1={kind_cate1} and can_be_ordered=1",
                eng,
            )
            delivery_cycle = np.unique(delivery_cycle["delivery_cycle"].values)
            delivery_cycle = min(delivery_cycle)  # 只有冷藏存在多个值, 1, 2, 3 取1, 其他均为单一值
            start_time = time.time()
            logging.info(
                f"开始计算, store_id: {store_id}, date: {query_date}, kind_cate1: {kind_cate1}, dev 环境: {setting == dev_setting}"
            )
            logging.info(
                f"bash command: {create_bash(query_date, kind_cate1, store_id, setting == dev_setting)}"
            )
            status = os.system(
                create_bash(
                    query_date=query_date,
                    kind_cate1=kind_cate1,
                    store_id=store_id,
                    dev_setting=(setting == dev_setting),
                )
            )
            elapsed = time.time() - start_time
            if status != 0:
                logging.info(
                    f'计算出现问题, store_id: {store_id}, date: {query_date}, kind code cate1: {kind_cate1}, 环境: {setting["db"]}'
                )
                break
            logging.info(f"返回耗时: {elapsed}")
            if elapsed < 60:
                calculate_time = elapsed
            elif setting == dev_setting:
                calculate_time = pd.DataFrame()
                while calculate_time.empty:
                    calculate_time = pd.read_sql(
                        f'select cal_time from calculate_time where dt = "{str(query_date)}" and store_id={store_id} and kind_code_cate1={kind_cate1}',
                        eng,
                    )
                    # 等待写库
                    time.sleep(0.1)
                    logging.warning(
                        f"未查询到计算时间, store_id: {store_id}, date: {query_date}, kind_code_cate1: {kind_cate1}"
                    )
                calculate_time = min(calculate_time["cal_time"].values)
            else:
                calculate_time = elapsed
            logging.info(f"计算时间, {calculate_time}")
            arrival_sale_day = [
                "sale_predict_qtty_t1",
                "sale_predict_qtty_t2",
                "sale_predict_qtty_t3",
            ][delivery_cycle]
            dev_prod = int(setting["db"] == "marsboard_dev")
            df_temp = pd.DataFrame()
            while df_temp.empty:
                df_temp = pd.read_sql(
                    f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
                    eng,
                )
                logging.warning(f"未查询到order list 里的信息")
                if pd.read_sql(
                    f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
                    prod_eng,
                ).empty:
                    logging.info(f"生产环境本品类亦无数据, {kind_cate1}")
                    break
                time.sleep(0.1)
            df_temp["dev_prod"] = dev_prod
            df_temp["calculate_time"] = float(calculate_time)
            df_temp.columns = columns

            df = pd.concat([df_temp, df], axis=0, ignore_index=True)
            print(df)
df.to_excel(f"{store_id}_bake.xlsx", index=False)

enter image description here

enter image description here enter image description here

5
  • Could you attach a screenshot, thanks. Commented Dec 6, 2021 at 7:43
  • Added, as you can see it's still generating the file, everytime I edit and save this file, it will generate a new file by df.to_excel Commented Dec 6, 2021 at 7:56
  • Sorry, could you attach the screenshot of terminal? Commented Dec 6, 2021 at 8:03
  • the problem is that I don't even open one terminal for the vscode and it's still generating the file, I attatch my code in this file as well Commented Dec 6, 2021 at 8:21
  • Could you open your terminal to have a look? Commented Dec 6, 2021 at 8:33

4 Answers 4

4

I have the same issue. It's now fixed. To do my test I used pytest and it was able to read my file when it started with test_. Because I'm stupid I named it a random filename test_func.py and in this one, I wrote "from main.py import *". So when I saved, and used pytest to run my test, my main file was run too.

To fix this I just renamed my file in teste-func.py and it works.

Sorry my English is terrible. I hope my comment is helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

This was very helpful, I thought I was going crazy because my pytest were constantly running on a separate thread as I was connected to hardware. Hitting save meant it was triggering this pytest every time. This is very dangerous behavior and glad I found this comment. I renamed it to anything but test_ to fix the code.
2

I avoid this issue by adding

if __name__ == '__main':
   fun()

I guess this file will be import or load or something else, then it gets run. Anyway, this is not important.

2 Comments

yes, you are right
This is a low-key answer that shows a really good way to deal with this issue. The backstory here is that when you import a module, python will run the code in that module. If you want to avoid having python run your code when all you're doing is importing it into a script containing your unit tests, then move the code in the script that would normally execute when you run the script into a function, e.g. fun(), and then add the code in this answer that checks to see if dunder-name equals main. More background: pythontutorial.net/python-basics/python-__name__
0

Perhaps , You have mistakenly installed an extension 'Run on Save' . I think that's causing the Problem.

3 Comments

This should be a comment. Not an answer
no, I checked my extension, and the weired thing is that it only happpens for this file
Try Copying the Code and pasting it again in a different .py file.
0

Just to confirm, the root cause in my case was that I was importing the module in my test files using PyTest. It seems that with every new update, the module is imported again dynamically. So, adding things like previously suggested as

if __name__ == '__main':
   fun()

Will help. You can also add the following to settings.json of VSCODE:

"python.testing.autoTestDiscoverOnSaveEnabled": false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.