[python] Launch Pycharm from command line (terminal)

I want to try out PyCharm for sage mathematics development. Normally I run eclipse to do sage development, but now I want to try it with PyCharm.

To launch eclipse with sage environment variables, in command line I normally do the following:

sage -sh
cd /path/to/eclipse
./eclipse

The first line loads the sage environment variables, the remainder launches eclipse. How can I do the same thing for pyCharm? (note I am using a Mac and Ubuntu for sage development; the commands above are agnostic to both OSes)

  1. Link 1 is close to the solution I am looking for, however I cannot find a pyCharm.sh anywhere.
  2. Link 2: Jetbrains does not give clear instructions either.

This question is related to python command-line environment-variables pycharm sage

The answer is


Update: My answer no longer works as of PyCharm 2018.X

On MacOS, I have this alias in my bashrc:

alias pycharm="open -a /Applications/PyCharm*.app"

I can use it like this: pycharm <project dir or file>

The advantage of launching PyCharm this way is that you can open the current dir in PyCharm using pycharm . (unlike /Applications/PyCharm*.app/Contents/MacOS/pycharm . which opens the PyCharm application dir instead)


Update: I switched to JetBrains Toolbox to install PyCharm. Finding PyCharm has gotten a bit more complex, but so far I was lucky with this monster:

alias pycharm="open -a \"\$(ls -r  /Applications/apps/PyCharm*/*/*/PyCharm*.app | head -n 1 | sed 's/:$//')\""

On Mac OSX

Update 2019/05 Now this can be done in the JetBrains Toolbox app. You can set it once with the Toolbox, for all of your JetBrain IDEs.


As of 2019.1 EAP, the Create Commmand Line Launcher option is not available in the Tools menu anymore. My solution is to use the following alias in my bash/zsh profile:

Make sure that you run chmod -x ...../pycharm to make the binary executable.

# in your ~/.profile or other rc file to the effect.

alias pycharm="open -a '$(ls -r /Users/geyang/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/**/PyCharm*.app/Contents/MacOS/pycharm)'"

After installing on kubuntu, I found that my pycharm script in ~/bin/pycharm was just a desktop entry:

[Desktop Entry]                                                                                                                                                                                                 
Version=1.0
Type=Application
Name=PyCharm Community Edition
Icon=/snap/pycharm-community/79/bin/pycharm.png
Exec=env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f
Comment=Python IDE for Professional Developers
Categories=Development;IDE;
Terminal=false
StartupWMClass=jetbrains-pycharm-ce

Obviously, I could not use this to open anything from the command line:

$ pycharm setup.py
/home/eldond/bin/pycharm_old: line 1: [Desktop: command not found
/home/eldond/bin/pycharm_old: line 4: Community: command not found

But there's a hint in the desktop entry file. Looking in /snap/pycharm-community/, I found /snap/pycharm-community/current/bin/pycharm.sh. I removed ~/bin/pycharm (actually renamed it to have a backup) and then did

ln -s /snap/pycharm-community/current/bin/pycharm.sh pycharm

where again, I found the start of the path by inspecting the desktop entry script I had to start with.

Now I can open files with pycharm from the command line. I don't know what I messed up during install this time; the last two times I've done fresh installs, it's had no trouble.


You can launch Pycharm from Mac terminal using the open command. Just type open /path/to/App

Applications$ ls -lrt PyCharm\ CE.app/
total 8
drwxr-xr-x@ 71 amit  admin  2414 Sep 24 11:08 lib
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 help
drwxr-xr-x@ 12 amit  admin   408 Sep 24 11:08 plugins
drwxr-xr-x@ 29 amit  admin   986 Sep 24 11:08 license
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 skeletons
-rw-r--r--@  1 amit  admin    10 Sep 24 11:08 build.txt
drwxr-xr-x@  6 amit  admin   204 Sep 24 11:12 Contents
drwxr-xr-x@ 14 amit  admin   476 Sep 24 11:12 bin
drwxr-xr-x@ 31 amit  admin  1054 Sep 25 21:43 helpers
/Applications$
/Applications$ open PyCharm\ CE.app/

Navigate to the directory on the terminal cd [your directory]

Navigate to the directory on the terminal

use charm . to open the project in PyCharm

Simplest and quickest way to open a project in PyCharm


Update

It is now possible to create command line launcher automatically from JetBrains Toolbox. This is how you do it:

  1. Open up the toolbox window;
  2. Go to the gear icon in the upper right (the settings window for toolbox itself);
  3. Turn on Generate shell scripts;
  4. Fill the Shell script location textbox with the location where you want the launchers to reside. You have to do this manually it will not fill automatically at this time!

On Mac the location could be /usr/local/bin. For the novices, you can use any path inside the PATH variable or add a new path to the PATH variable in your bash profile. Use echo $PATH to see which paths are there.

Note! It did not work right away for me, I had to fiddle around a little before the scripts were generated. You can go to the gearbox of the IDEA (PyCharm for example) and see/change the launcher name. So for PyCharm, the default name is pycharm but you can change this to whatever you prefer.

Original answer

If you do not use the toolbox you can still use my original answer.

~~For some reason, the Create Command Line Launcher is not available anymore in 2019.1.~~ Because it is now part of JetBrains Toolbox

This is how you can create the script yourself:

If you already used the charm command before use type -a charm to find the script. Change the pycharm version in the file paths. Note that the numbering in the first variable RUN_PATH is different. You will have to look this up in the dir yourself.

RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'

If you did not use the charm command before, you will have to create it.

Create the charm file somewhere like this: /usr/local/bin/charm

Then add this code (change version number to your version as explained above):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import struct
import sys
import os
import time

# see com.intellij.idea.SocketLock for the server side of this interface

RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'


def print_usage(cmd):
    print(('Usage:\n' +
           '  {0} -h | -? | --help\n' +
           '  {0} [project_dir]\n' +
           '  {0} [-l|--line line] [project_dir|--temp-project] file[:line]\n' +
           '  {0} diff <left> <right>\n' +
           '  {0} merge <local> <remote> [base] <merged>').format(cmd))


def process_args(argv):
    args = []

    skip_next = False
    for i, arg in enumerate(argv[1:]):
        if arg == '-h' or arg == '-?' or arg == '--help':
            print_usage(argv[0])
            exit(0)
        elif i == 0 and (arg == 'diff' or arg == 'merge' or arg == '--temp-project'):
            args.append(arg)
        elif arg == '-l' or arg == '--line':
            args.append(arg)
            skip_next = True
        elif skip_next:
            args.append(arg)
            skip_next = False
        else:
            path = arg
            if ':' in arg:
                file_path, line_number = arg.rsplit(':', 1)
                if line_number.isdigit():
                    args.append('-l')
                    args.append(line_number)
                    path = file_path
            args.append(os.path.abspath(path))

    return args


def try_activate_instance(args):
    port_path = os.path.join(CONFIG_PATH, 'port')
    token_path = os.path.join(SYSTEM_PATH, 'token')
    if not (os.path.exists(port_path) and os.path.exists(token_path)):
        return False

    try:
        with open(port_path) as pf:
            port = int(pf.read())
        with open(token_path) as tf:
            token = tf.read()
    except (ValueError):
        return False

    s = socket.socket()
    s.settimeout(0.3)
    try:
        s.connect(('127.0.0.1', port))
    except (socket.error, IOError):
        return False

    found = False
    while True:
        try:
            path_len = struct.unpack('>h', s.recv(2))[0]
            path = s.recv(path_len).decode('utf-8')
            if os.path.abspath(path) == os.path.abspath(CONFIG_PATH):
                found = True
                break
        except (socket.error, IOError):
            return False

    if found:
        cmd = 'activate ' + token + '\0' + os.getcwd() + '\0' + '\0'.join(args)
        if sys.version_info.major >= 3: cmd = cmd.encode('utf-8')
        encoded = struct.pack('>h', len(cmd)) + cmd
        s.send(encoded)
        time.sleep(0.5)  # don't close the socket immediately
        return True

    return False


def start_new_instance(args):
    if sys.platform == 'darwin':
        if len(args) > 0:
            args.insert(0, '--args')
        os.execvp('/usr/bin/open', ['-a', RUN_PATH] + args)
    else:
        bin_file = os.path.split(RUN_PATH)[1]
        os.execv(RUN_PATH, [bin_file] + args)


ide_args = process_args(sys.argv)
if not try_activate_instance(ide_args):
    start_new_instance(ide_args)

This worked for me on my 2017 imac macOS Mojave (Version 10.14.3).

  1. Open your ~/.bash_profile: nano ~/.bash_profile

  2. Append the alias: alias pycharm="open /Applications/PyCharm\ CE.app"

  3. Update terminal: source ~/.bash_profile

  4. Assert that it works: pycharm


To open PyCharm from the terminal in Ubuntu 16.04, cd into

{installation home}/bin

which in my case was

/home/nikhil/pycharm-community-2018.1.1/bin/

and then type:

./pycharm.sh

I normally alias using built-in application launcher (open) from OS X:

alias pc='open -a /Applications/PyCharm\ CE.app'

Then I can type:

pc myfile1.txt myfiles*.py

Though you can't (easily) pass args to PyCharm, if you want a quick way to open files (without needing to use full pathnames to the file), this does the trick.


Inside the IDE, you can click in:

Tools/Create Command-line Launcher...

Create Command-line Launcher


The included utility that installs to /usr/local/bin/charm did not work for me on OS X, so I hacked together this utility instead. It actually works!

#!/usr/bin/env bash

if [ -z "$1" ]
then
  echo ""
  echo "Usage: charm <filename>"
  exit
fi
FILENAME=$1

function myreadlink() {
  (
  cd $(dirname $1)         # or  cd ${1%/*}
  echo $PWD/$(basename $1) # or  echo $PWD/${1##*/}
  )
}

FULL_FILE=`myreadlink $FILENAME`;

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE

open /Applications/PyCharm\ CE.app/ opens up the primary Pycharm Dialogue box to choose the project..

worked for me with macOS 10.13.6 & Pycharm 2018.1


Steps for someone using zsh on Mac:

  1. emacs ~/.zshrc&
  2. Put this in zshrc---> alias pycharm="/Applications/PyCharm\CE.app/Contents/MacOS/pycharm"
  3. source ~/.zshrc
  4. Launch by typing pycharm in command window

Useful information for some:

On Linux, installing PyCharm as a snap package automatically creates the command-line launcher named pycharm-professional, pycharm-community, or pycharm-educational. The Tools | Create Command-line Launcher command is therefore not available.


pycharm download & Open in UBUNTU

Download:

Open:

  1. Navigate to bin directory in the extracted folder.

  2. run : ./pycharm.sh


Use Tools -> Create Command-line Launcher which will install a python script where you can just launch the current working folder using charm .

Very important!

Anytime you upgrade your pyCharm you have to re-create that command line tool since its just a python script that points to a pyCharm configuration which might be outdated and will cause it to fail when you attempt to run charm .


Easy solution without need for pathes:

open -b com.jetbrains.pycharm



You can set it as alias for every-day easier usage (put to your .bash_rc etc.):

alias pycharm='open -b com.jetbrains.pycharm'

Usage:

pycharm .
pycharm file.py

You're right that the JetBrains help page isn't very clear. On OS X, you'll want to use the launcher at:

/Applications/PyCharm.app/Contents/MacOS/pycharm

Or, for community edition:

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm

Unfortunately, adding a symlink to this binary wouldn't work for me (the launcher would crash). Setting an alias worked, though. Add this in your .bash_profile (or whatever shell you use):

alias pycharm="/Applications/PyCharm CE.app/Contents/MacOS/pycharm"

Then, you can run commands with simply pycharm.

With this you can do things like open a project:

pycharm ~/repos/my-project

Or open a specific line of a file in a project:

pycharm ~/repos/my-project --line 42 ~/repos/my-project/script.py

Or view the diff of two files (they don't need to be part of a project):

pycharm ~/some_file.txt ~/Downloads/some_other_file.txt

Note that I needed to pass absolute paths to those files or PyCharm couldn't find them..


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

Examples related to pycharm

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website Pycharm/Python OpenCV and CV2 install error Import numpy on pycharm Global npm install location on windows? Pycharm and sys.argv arguments PyCharm error: 'No Module' when trying to import own module (python script) Using (Ana)conda within PyCharm Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

Examples related to sage

Launch Pycharm from command line (terminal)