I thought it will be as simple as adding these locations to Path or PYTHONPATH. I added them to PYTHONPATH and added PYTHONPATH to Path.
When running SET of window's terminal I can see my newly set paths;
E:\Tests> SET
Path=E:\Tests\PythonTests
PYTHONPATH=E:\Tests\PythonTests
(I simplified the list for readability)
I then create a very simple python file test.py inside E:\Tests\PythonTests with a single line:
print ("Hello world")
Now, if I cd \Tests\PythonTests I can run it successfully:
E:\Tests\PythonTests> python test.py
Hello world
If I cd \Tests I can:
E:\Tests> python pythonTests/test.py
Hello world
But if I try
E:\Tests> python test.py
python: can't open file 'test.py': [error 2] No such file or directory
Python version:
E:\Tests\PythonTests>python --version
Python 3.8.0
Am I'm missing something? What am I doing wrong?
The PYTHONPATH env var does not control where the python command searches for arbitrary Python programs. It controls where modules/packages are searched for. Google "pythonpath environment variable" for many explanations what the env var does. This is from python --help:
PYTHONPATH : ':'-separated list of directories prefixed to the
default module search path. The result is sys.path.
Specifying a file from which to read the initial Python script is not subject to any env var manipulation. In other words, running python my_prog.py only looks in the CWD for my_prog.py. It does not look at any other directory.
#!/usr/bin/python
import requests, zipfile, StringIO, sys
extractDir = "myfolder"
zip_file_url = "download url"
response = requests.get(zip_file_url)
zipDocument = zipfile.ZipFile(StringIO.StringIO(response.content))
zipinfos = zipDocument.infolist()
for zipinfo in zipinfos:
extrat = zipDocument.extract(zipinfo,path=extractDir)
System configuration
Ubuntu OS 16.04
Python 2.7.12
$ python extract.py
when I run the code on Terminal with above command, it works properly and create the folder and extract the file into it.
Similarly, when I create a cron job using sodu rights the code executes but don't create any folder or extracts the files.
crontab command:-
40 10 * * * /usr/bin/sudo /usr/bin/python /home/ubuntu/demo/directory.py > /home/ubuntu/demo/logmyshit.log 2>&1
also tried
40 10 * * * /usr/bin/python /home/ubuntu/demo/directory.py > /home/ubuntu/demo/logmyshit.log 2>&1
Notes :
I check the syslog, it says the cron is running successfully
The above code gives no errors
also made the python program executable by chmod +x filename.py
Please help where am I going wrong.
Oups, there is nothing really wrong in running a Python script in crontab, but many bad things can happen because the environment is not the one you are used to.
When you type in an interactive shell python directory.py, the PATH and all required PYTHON environment variable have been set as part of login and interactive shell initialization, and the current directory is your home directory by default or anywhere you currently are.
When the same command is run from crontab, the current directory is not specified (but may not be what you expect), PATH is only /bin:/usr/bin and python environment variables are not set. That means that you will have to tweak environment variables in crontab file until you get a correct Python environment, and set the current directory.
I had a very similar problem and it turned out cron didn’t like importing matplotlib, I ended up having to specify Agg backend. I figured it out by putting log statements after each line to see how far the program got before it crapped out. Of course, my log was empty which tipped me off that it crashed on imports.
TLDR: log each line inside the script
I am working through Practical Maya Programming, and trying to set a 'development root' on my PC, I have followed the instructions (below) exactly but it is not working - At the point where I type 'mayapy.exe' I get the warning "'mayapy.exe' is not recognized as an internal or external command, operable program or batch file."
From the book:
Let's decide where we will do our coding. We'll call this location the development root for the rest of the book. To be concise, I'll choose C:\mayapybook\pylib to house all of our Python code.
Create the development root folder, and inside of it create an empty file named minspect.py.
Now, we need to get C:\mayapybook\pylib onto Python's sys.path so it can be imported. The easiest way to do this is to use the PYTHONPATH environment variable. From a Windows command line you can run the following to add the path, and ensure it worked:
> set PYTHONPATH=%PYTHONPATH%;C:\mayapybook\pylib
> mayapy.exe
>>> import sys
>>> 'C:\\mayapybook\\pylib' in sys.path
True
>>> import minspect
>>> minspect
<module 'minspect' from '...\minspect.py'>
EDIT
This is how it is working for me at the moment:
PS C:\Users\Me> set PYTHONPATH=%PYTHONPATH%;C:\mayapybook\pylib
C:\mayapybook\pylib : The term 'C:\mayapybook\pylib' is not recognized as the name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:29
+ set PYTHONPATH=%PYTHONPATH%;C:\mayapybook\pylib
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\mayapybook\pylib:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
So the code from the book is not working but the code from the post by DrHaze seems to:
PS C:\Users\Me> setx PATH "%PATH%C:\mayapybook\pylib\"
SUCCESS: Specified value was saved.
But when I run the Maya Python Interpreter and check if C:\mayapybook\pylib\ is in sys path it returns false:
>>> 'C:\\mayapybook\\pylib' in sys.path
False
This error "'mayapy.exe' is not recognized as an internal or external command, operable program or batch file." means that the path where mayapy.exe is located is not included in the PATH environment variable. Your system tries to look in all the folders included in the PATH variable but can't find an executable called mayapy.exe.
The executable mayapy.exe is generally located here:
C:\Program Files\Autodesk\Maya(VERSION)\bin\mayapy.exe
on my computer it's located here: C:\Program Files\Autodesk\Maya2014\bin\mayapy.exe
To add the mayapy.exe location to your path, use one of the following commands:
setx PATH "%PATH%;C:\Program Files\Autodesk\Maya2014\bin\" if you
want to change it permanently
set PATH "%PATH%;C:\Program Files\Autodesk\Maya2014\bin\" only works for the current instance of the cmd session.
EDIT
The error you show in your edit is the source of the problem. Windows failed to set the environment variable PYTHONPATH. Hence, when you execute 'C:\\mayapybook\\pylib' in sys.path it returns False. sys.path is in fact containing the value of PYTHONPATH. That's why it returns False.
Now, why did it fail to set this environment variable?
First I can see that you are using Windows Powershell, keep this in mind.
The command I gave you is:
set PATH "%PATH%;C:\Program Files\Autodesk\Maya2014\bin\"
You wrote:
set PYTHONPATH=%PYTHONPATH%;C:\mayapybook\pylib
What it should be:
set PYTHONPATH "%PYTHONPATH%;C:\mayapybook\pylib\"
The syntax is a bit different and this last command should work.
As an explaination, your book gives you some commands to type in the vintage/old-style windows terminal: cmd.exe
As you are using Windows Powershell, some commands might have a different syntax.
Now what you can do is:
Use cmd.exe (Right click on the title bar -> Properties to custom it)
Use Powershell but keep in mind that the syntax might be a bit different than in your book
If you are using Powershell, there are different commands and strategies for managing environment variables.
You can set a variable permanently with SetEnvironmentVariable
You can set for the current shell session with: $env:VARNAME =
VARVALUE
You can put the commands to set variables in a powershell profile
file.
I would go with the third option. All three are detailed below:
Option 1. To append the directory "C:\mayapybook\pylib\" to the existing
PYTHONPATH permanently for your account:
[Environment]::SetEnvironmentVariable("PYTHONPATH", $env:PYTHONPATH +";C:\mayapybook\pylib\", "User")
Option 2. To append the Maya bin folder to your PATH for only the current
shell session:
$env:PATH += ";C:\Program Files\Autodesk\Maya2016\bin\"
Option 3. Create a powershell profile and set your env vars there.
First you'll need to make sure powershell scripts can run locally:
Hit the windows button, start typing powershell, right click and open as administrator. Enter:
Get-ExecutionPolicy
If it is says Restricted or AllSigned, set it to RemoteSigned like so:
Set-ExecutionPolicy RemoteSigned
Close that shell. Now in another powershell (not admin) type:
cd ~\Documents
md WindowsPowerShell
cd WindowsPowerShell
New-Item -path "profile.ps1" -type file
notepad.exe profile.ps1
Paste into the file any commands you want to run whenever a new powershell is opened:
Write-Host "Hello From Your Profile"
$env:PATH += ";C:\Program Files\Autodesk\Maya2016\bin\"
$env:PYTHONPATH += ";C:\mayapybook\pylib\"
Now whenever you open a powershell, you'll get a silly message and those paths will be set. You can test by typing:
Write-Host $env:PATH
or to list all env vars:
Get-ChildItem Env:
You should now be able to run commands from the maya bin directory. For example, type: maya to start maya.
Some other useful powershell env var commands here.
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)
Link 1 is close to the solution I am looking for, however I cannot find a pyCharm.sh anywhere.
Link 2: Jetbrains does not give clear instructions either.
Edit (April 2020): It seems that launcher script creation is now managed in Toolbox App settings.
See the Toolbox App announcement for more details.
--
Open Application Pycharm
Find tools in menu bar
Click Create Command-line Launcher
Checking the launcher executable file which has been created in /usr/local/bin/charm
Open project or file just type $ charm YOUR_FOLDER_OR_FILE
Maybe this is what you need.
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..
Inside the IDE, you can click in:
Tools/Create Command-line Launcher...
Update
It is now possible to create command line launcher automatically from JetBrains Toolbox. This is how you do it:
Open up the toolbox window;
Go to the gear icon in the upper right (the settings window for toolbox itself);
Turn on Generate shell scripts;
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)
macOS
Easy solution without need for any paths:
open -b com.jetbrains.pycharm <file>
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:
# open current dir:
pycharm .
# open a file:
pycharm file.py
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.
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 .
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
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)'"
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.
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
Steps for someone using zsh on Mac:
emacs ~/.zshrc&
Put this in zshrc---> alias pycharm="/Applications/PyCharm\CE.app/Contents/MacOS/pycharm"
source ~/.zshrc
Launch by typing pycharm in command window
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
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/:$//')\""
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.
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
pycharm download & Open in UBUNTU
Download:
download pycharm linux version here : https://www.jetbrains.com/pycharm/download/#section=linux
Extract the download the downloaded tar file using : tar -xvf pycharm-Example-tar.gz
Open:
Navigate to bin directory in the extracted folder.
run : ./pycharm.sh
you can include following command in your script
root#aachutha-Inspiron-N5010:~# pycharm-community &
[1] 5698
This worked for me on my 2017 imac macOS Mojave (Version 10.14.3).
Open your ~/.bash_profile:
nano ~/.bash_profile
Append the alias:
alias pycharm="open /Applications/PyCharm\ CE.app"
Update terminal:
source ~/.bash_profile
Assert that it works:
pycharm
Via Terminal (Linux)
Create a function with bash.
charm() { /usr/local/bin/charm; }
export charm
Via Pycharm
Go into Pycharm
Tap Double Shift (Shift + Shift)
Search For Create Command-line Launcher
Type in Command-line Launcher: /usr/local/bin/charm
Click Ok
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/
if i run
django-admin.py startproject mysite
django-admin.py (which is located in C:\python27\scripts/django-admin.py) will open in a file editor (now it opens in python ide, but in the past i had pype so it would open in pype) so the file opens:
#!C:\Python27\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
i see no output in the command prompt at all, so lets say i typed
C:\abc:>django-admin.py startproject mysite
when I hit enter i see C:\abc>
and the project will not be created using the command prompt
this issue is not new for me, i'm creating my python projects using pydev, i would love to fix this issue with the command prompt though :)
#slugonamission
when I run
pyhon django-admin.py startproject mysite
the output of the command prompt is
python: can't open 'django-admin.py' file : [Errno 2] No such file or directory
I don't think Windows supports the shebang line. Try invoking it with python django-admin.py ...
I'm using python 2.7 , django 1.7 in windows7.
WAY-1:
1) Go to C:\Python27\Scripts (or your installation directory)
2) open cmd and enter python django-admin-script.py startproject ProjectName
3)Your project folder with all necessary files ll be created there.
The problem is in windows, django-admin.py is supplied as django-admin-script.py
WAY2:
1)Open cmd at any location you want.
2)enter django-admin startproject ProjectName
3)Your project folder with all necessary files ll be created there.
Its because the .exe file is supplied.
This often happens in Windows.
Open cmd at any location you want.
enter django-admin startproject ProjectName (don't add the .py extension to the admin)
Your project folder with all necessary files will be created there.
This is because the .exe file is supplied inside the directory.
For anyone else who has this issue:
Try taking out the '.py'
django-admin startproject helloworld
firstly find out where the django-admin.py is located then go to that path and then run the command django-admin.py startproject projectName
i hope it will help you......best luck
Using the Bitnami Django Stack
> cd C:\Users\user_user_name\Bitnami Django Stack projects
C:\Users\user_user_name\Bitnami Django Stack projects>
> python C:\Bitnami\djangostack-1.8.17-0\apps\django\Django-1.8.17-py2.7.egg\EGG-INFO\scripts\django-admin.py --version
> python C:\Bitnami\djangostack-1.8.17-0\apps\django\Django-1.8.17-py2.7.egg\EGG-INFO\scripts\django-admin.py startproject projectname
That works for me.