![](/img/trans.png)
[英]Launching Python script from Windows command line: script starts, then fails
[英]Python script to run command line which starts python script with specific python version
我需要協助。 是否有可能讓python在Windows中啟動命令行並讓命令行在我的PC上以另一個python版本執行腳本?
例子:我的電腦上有兩個版本的python。 一個在Anaconda內部,另一個在純Python中。 現在,我有一些腳本要按特定的順序執行。 我的問題是,Google Analytics(分析)API不能與Anaconda一起使用,而其他一些軟件包(如Simpy)也不能與純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()返回命令的退出值,因此,如果您需要腳本中的某些輸出,將無法使用。
我建議你看一下子流程
# 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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.