简体   繁体   English

我如何使用python脚本来做,就像我使用shell一样?

[英]How can I use a python script to do as if I was using a shell?

I'm kinda new to python and shell (and programming in general...) My problem is, I was given an environment, which is working fine, and I need to activate this environment in order to start a python script. 我对python和shell(以及一般编程......)有点新手。我的问题是,我得到了一个工作正常的环境,我需要激活这个环境才能启动python脚本。

Doing this manually in the shell (I'm on windows) works perfectly (ie activating the environment using "activate myenv", and then starting my script using "python myprog.py". 在shell中手动执行此操作(我在Windows上)可以正常工作(即使用“激活myenv”激活环境,然后使用“python myprog.py”启动我的脚本)。

Now, I would like to do all of that just from a python script. 现在,我想从python脚本中完成所有这些。 I would like to start a script in my shell which activate my environment in that shell and then start myprog.py 我想在我的shell中启动一个脚本,在该shell中激活我的环境,然后启动myprog.py

I've check on the internet and found "os.system" and "subprocess.run", but both don't work 我在互联网上检查并找到“os.system”和“subprocess.run”,但两者都不起作用

myprog.py myprog.py

import subprocess
subprocess.run(['activate','myenv'], shell=True)

print('done')

This is a short script to activate my environment according to what i found on the internet. 这是根据我在互联网上找到的内容激活我的环境的简短脚本。 Must put shell=True otherwise I have an error : FileNotFoundError: [WinError 2] The system cannot find the file specified 必须把shell = True否则我有一个错误: FileNotFoundError: [WinError 2] The system cannot find the file specified

Executing myprog.py using the command "python myprog.py" works perfectly, but the environment in my shell isn't activated. 使用命令“python myprog.py”执行myprog.py工作正常,但我的shell中的环境未激活。 But if I write directly in my shell "activate myenv" the environment activates 但如果我直接在我的shell中写“激活myenv”,环境就会激活

It's because it only activates env for your subprocess command. 这是因为它只激活子进程命令的env。 The command is created in a child process, not in the main process (where you run your python script). 该命令在子进程中创建,而不是在主进程(运行python脚本的位置)中创建。

When this line ends, your child process is terminated: 当此行结束时,您的子进程将终止:

subprocess.run(['activate','myenv'], shell=True)

There was an old post but it's hacky. 有一个老帖子,但它很hacky。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM