Reputation: 49
I am creating a script that will call an API and return some results. I have the script working with pycharm on my computer but I am running into a few problems but I want to focus on this problem first.
1) I am unable to set Python3 as my default python.
I am using a Mac. When I go into terminal I enter $ python --version
and it returns Python 2.7.10
I then enter $ alias python=python3
, and when I run $python --version
it returns Python 3.7.2
When I create a py.script with the os module, it does not work. See my code below.
import os
os.system('alias python=python3')
print(os.system('python --version')
It prints 2.7.10
I also tried to run the os.system('alias python="python3"')
Upvotes: 2
Views: 2156
Reputation: 40843
On -nix machines (including OSX), one way to change the version of the interpreter that the script runs with is to add a shebang as the first line of your script.
Eg.
#! /usr/bin/env python3
import sys
print(sys.version)
Then to run your script do:
~/$ chmod u+x myscript.py
~/$ ./myscript.py
You only need to run the chmod
command the first time. It enables you to execute the file. Whenever you run your script directly (rather than as an argument to python) your script will be run using the version specified by the shebang.
Upvotes: 2
Reputation: 54233
This isn't surprising, because os.system
opens its own shell, and running alias
in that way only affects the currently running terminal. Each call to os.system
would be in a separate shell.
I'm not sure what your ultimate goal is, but you almost certainly don't need to change what python
means to a shell to do it. If you DO, you'll have to run both commands at once.
import subprocess
cp = subprocess.run("alias python=python3 && /path/to/script")
Upvotes: 1
Reputation: 700
Interesting - apparently os.system ignores the alias? Just checked it in Linux and got the same results.
Try sys
instead of os
:
import sys
print(sys.version)
Upvotes: 0
Reputation: 1593
welcome to SO! Pycharm needs you to specify which interpreter to use as default, as it wouldn't choose the system one by default.
So if you want python3
, you can run which python3
, and use the path as a settings for the current project. How to do that step by step is here:
https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html
Hope it help, post a comment if you need more details.
Upvotes: 1