Python 脚本到 运行 命令行启动 python 具有特定 python 版本的脚本

Python script to run command line which starts python script with specific python version

我需要一些帮助。是否有可能让 python 在 windows 中启动命令行并让命令行在我的电脑上的另一个 python 版本中执行脚本?

示例:我的电脑上有两个版本的 python。一个在 Anaconda 中,另一个是纯 Python。现在我有一些脚本要按特定顺序执行。我的问题是,Google Analytics API 不适用于 Anaconda,而其他一些包(如 Simpy)不适用于 pure Python。所以我需要为一个项目使用两个不同版本的 python。

现在我想写一个小 python 文件,它打开命令行并在我的不同 Python 版本上按特定顺序执行脚本。

我知道如何在命令行上 运行 一个 python 文件。这是通过

C:\path_to_python\python.exe C:\path_to_file\file.py

但是我怎样才能使 python 脚本在命令行中执行上述行?

希望有人能帮助我。

谢谢。

import os
os.system("C:\path_to_python\python.exe C:\path_to_file\file.py")

os.system() returns 命令的退出值,因此如果您需要脚本的一些输出,这将不起作用。

我建议你看看subprocess

# this is new to python 3.5
import subprocess
cmd = subprocess.run(["C:/path_to_python/python.exe", "C:/path_to_script/script.py"], stdout=subprocess.PIPE)
return_string = cmd.stdout

# alternative for getting command output in python 3.1 and higher
import subprocess
return_string = subprocess.check_output(["C:/path_to_python/python.exe", "C:/path_to_script/script.py"])

相反,您可以尝试编写一个 批处理文件,您可以在其中指定您想要 运行 文件的顺序以及您必须使用哪个版本 运行 文件。 让我们先说我想 运行 在 python2.7 中的一个文件,然后在 python3.4 中,我的文件在 d:/pythonfiles

RunningSequence.bat

d:
cd D:\pythonfiles
c:\python27\python.exe python27file.py
c:\python34\python.exe python34file.py 

试试这个让我知道:

import sys

with open(sys.argv[1], 'r') as my_file:
     exec(my_file.read())