如何激活Python虚拟环境并同时执行脚本? - python

我试图在Powershell中自动加载我的Python虚拟环境并同时执行python查询,但是我对此没有任何运气。这是我的代码:

# my_testing_file.py

# Activate the virtual environment
import os
script_directory = os.path.dirname(os.path.abspath(__file__))
activate_this_file = os.path.join(script_directory, 'C:\Temp\Development\Python_scripts\env\Scripts\activate_this.py')

# Start executing the main code
import pypyodbc
from openpyxl.workbook import Workbook

def main():
    cursor = initiate_connection_db()
    unposted_hours_results = retrieve_results_query(cursor)
    ...

if __name__ == "__main__":
    main()

所有代码都在一个文件中,基本上我想在Powershell python my_testing_file.py中执行,因此它将加载虚拟环境并执行其余代码。

当从Powershell执行此代码时,命令提示符将显示几秒钟,然后关闭,其余代码将永远不会执行。修复此代码的任何帮助将不胜感激。

参考方案

正如@dfundako指出的,激活后的脚本可以完成激活虚拟环境并立即执行脚本的全部操作,但是,我发现了另一个替代方法,我认为这不是最好的选择,但它可以满足我的要求。我必须将python脚本及其库打包到一个.exe文件中,因此,一旦用户单击它,程序便会执行所需的任务。

在我的虚拟环境中,我执行了名为setup.py的文件,将my_testing_file.py构建为.exe:

# Python 3.6.7
# The cx_Freeze library did the trick to pack all the libraries and the script. 
# Put down all the scripts that your 

import sys, os
import openpyxl
import cx_Freeze
import my_testing_file.py
from subprocess import call

base = None

if sys.platform == 'win32':
    base = "Win32GUI"

# my_testing_file is the main script that executes my desired task.
executables = [cx_Freeze.Executable("my_testing_file.py", base=base)]

cx_Freeze.setup(
    name = "Testing Deploy",
options = {"build_exe":
           {"packages":
            ["openpyxl", "subprocess"]
            }
           },
version = "0.01",
description = " Testing executable alternative",
executables = executables
)

我相信使用Docker也可以完成类似的操作,但是我缺乏实现相同目标所需的知识。随时改善此答案,或将代码放置在Docker替代方案或上述激活后脚本中。

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…