Enthought Canopy - passing sys.argv from PySide Qt program - pyside

I've recently been looking at the Enthought distro of iPython. Today I decided to see if I could get some Qt GUI progs running and was successful after making minor changes. Simple example:
import sys
from PySide import QtGui # was 'from PyQT4 import QtGui'
# app = QtGui.QApplication(sys.argv) -- not needed
win = QtGui.QWidget()
win.resize(320, 240)
win.setWindowTitle("Hello MIT 6X!")
win.show()
sys.exit() # was 'sys.exit(app.exec_())'
But I would like to be able to pass sys.argv in some cases. Most example code I see is in the form of the commented out 'app = ' line above. If I include it, I get
'RuntimeError: A QApplication instance already exists.'
Suggestions for passing arguments appreciated.

Two separate issues:
1) Passing command line arguments: As you have probably noticed, when you do the "Run" command from the Canopy editor, all it does is issue the IPython %run magic command. You can type the same command in the IPython shell, plus command line parameters, which your program will see. Or to save keystrokes, do this auto-generated Run command once, then press Up Arrow in the IPython shell to recall that auto-generated %run command, then enter your parameters after the filename, and then press Enter. You'll end up with an IPython magic command like this:
%run pathtoprog/myprogrampy p1 p2 p3
We (Enthought) are considering adding a setting for command-line parameters so that you could do "Run with parameters" and have the best of both worlds.
2) Existing QApplication: By default, Canopy's IPython is running in IPython's interactive Pylab mode, with a Qt backend. If you don't want this, you can just disable Pylab mode in the Canopy Preferences/Python menu, or change the Pylab mode to Inline (for matplotlib) instead of Interactive.
For maximum flexibility, with a bit more work, you could (as matplotlib does) introduce logic which checks whether a QApplication already exists, use it if it exists and create it if it does not.

Related

How can I activate Conda environment using python code?

How can I activate a Conda environment using python code?
Here are things I tried so far but they don't seem to change my environment:
import os
os.system('conda activate envname')
# Doesn't work but returns no errors.
import os
stream = os.popen('conda activate envname')
output = stream.read()
# Doesn't work but returns no errors.
import subprocess
process = subprocess.Popen(['conda', 'activate', 'envname'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
stdout, stderr = process.communicate()
# Doesn't work but returns no errors.
So how can I change my Conda environment using python, and I want it to work on all platforms (linux, mac, windows)?
EDIT 1:
So from this question it seems that all I'm doing is changing the environment temporarily during the existence of the subprocess. I want a way to change it in my current running shell...

Sourcing bash file inside PyQt4 GUI

I'm working on a GUI built with PyQt4 and Python 2.7 that launches various demos for a Clearpath Husky running ROS Indigo. The GUI switches between launching navigation demos and visualizing my physical robot. To do this, it has to switch between launching demos on a local ROS and the ROS on my Husky. When switching between the two different ROS instances I need to be able to "source" the devel/setup.bash for each OS so that the packages are built correctly and visualizing the Husky inside Rviz doesn't break (Errors with TF frames like "No tf data. Actual error: Fixed Frame [odom] does not exist" and with RobotModel "URDF Model failed to parse"). In my .bashrc, if I source the Husky's setup.bash, the visualization works fine until I try running a local demo. This also happens vice versa; while sourcing the local setup.bash will run the local demos just fine, the Husky's visualization breaks.
Is there a way to use python's subprocess (or another alternative) to source the appropriate devel/setup.bash within the GUI's instance so that the visualization won't break?
Yes, it should be sufficient to source the setup script just before executing the ROS command you want, for instance:
#!/usr/bin/env python
from subprocess import Popen, PIPE
shell_setup_script = "/some/path/to/workspace/devel/setup.sh"
command = "echo $ROS_PACKAGE_PATH"
cmd = ". %s; %s" % (shell_setup_script, command)
output = Popen(cmd, stdout=PIPE, shell=True).communicate()[0]
print(output)
As you see, shell=True is used, which will execute the cmd in a subshell. Then, cmd contains . <shell_setup_script>; <command> which sources the setup script before executing the command. Please note that the .sh file is sourced instead of .bash since generic POSIX shell is likely to be used by Popen.

Can't run a Python file in Windows command prompt [duplicate]

This question already has answers here:
How to run a python script from IDLE interactive shell?
(15 answers)
Closed 5 years ago.
I'm running Windows 7 64-bit with Python 3.4.1, 64-bit
cmd window
I've appended the PATH in system Environment Variable with ;C:\Python34 and saved, then gone into cmd and done the following, yet I keep getting an 'INVALID SYNTAX' message. Yes, I've searched the Q&A here and seen several threads with same problem, but haven't reached success trying their suggestions. As can be seen, I've tried 3 variations of the basic command "python ." Please help.
I think you're misunderstanding the idea.
If you want to execute a script "RUN_ME.py", run python RUN_ME.py directly in the command line. (type cmd into start and then python RUN_ME.py in the window you get)
If you want to type some lines of python and interpret them directly, type python without arguments. (or use the program shortcut you used here)
The mistake made here is the difference between the command line and the python REPL.
When you opened the terminal the way you did, probably by clicking on python terminal or whatever, you opened the python REPL (also available by executing python without arguments in command line), this is a place where you can execute code directly (no scripts). it used to be able to run python scripts as well but the command was phased out in python 3.x. Typically the REPL starts lines with >>>
To run a python script, you have to be in the command line and give the script as parameter to python, aka
python <script_name>. Getting the command line on windows can be done directly by typing cmd, or if you want to open it at a certain path, browse to the path you want in the file explorer and type cmd into the place where the path is displayed.
Okay, I understand now not to use 'python' plus the .py filename when already in the Python '>>>' prompt. Here's a simple try within Windows command prompt at navigating to the directory where the 'RUN_ME.py' file is located and attempting to run:
C:\>cd program files\trader workstation
C:\Program Files\Trader Workstation>cd ibridgepy
C:\Program Files\Trader Workstation\IBridgePy>python
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'C:\\Program Files\\Trader Workstation\\IBridgePy'
>>> RUN_ME.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'RUN_ME' is not defined

Alias to Launch Python .py Script

I am trying to create an Alias to launch mystepper6.py and moveit.py and sudo ps ax by placing the following alias' in sudo nano ~/.bashrc (Note: I am using Python 2 for this script.)
reboot='sudo reboot'
ax='sudo ps ax'
runstepper='python home/pi/mystepper6.py'
moveit='sudo python home/pi/moveit.py'
The alias reboot works fine but none of the others work at all. All I get is "bash: runstepper: command not found".
I am doing this because I am trying to control my webcam on my Raspberry Pi 2 using my iPhone with the iFreeRDP app. I use remote desktop connection from my Windows 10 laptop. The problem with this app and some other similar apps, is that the period and space keys do not function (it is a know reported issue). This makes typing full commands impossible.
Incidentally, I tried to use the VNC Viewer iPhone app and got my Raspberry Pi 2 hijacked when I loaded the required software onto the RPi2 requiring me to get a new SD card. Fortunately, I just cloned my SD card a few hours prior. Long story, but I am very weary about using VNC Viewer now.
Please help me with my alias' so I can either type one word with no spaces or periods or create a desktop short cut that I can double click so I can use it as a workaround for the deficiencies of these otherwise good apps. I am not sure the Ctrl + C works on the app keyboards either, so a short cut for that would be good as well.
to create aliases in your shell, you shall use the alias shell directive:
alias reboot='sudo reboot'
alias ax='sudo ps ax'
To run ps ax you do not need to sudo first. If you're running a standard kernel, any user can see the list of all processes without special privileges.
For the two python aliases:
alias runstepper='python home/pi/mystepper6.py'
alias moveit='sudo python home/pi/moveit.py'
^-- missing / here
do not forget about the first / in the path, or whenever you launch the aliased command, you'll have python look up for the script relatively to the current directory. i.e. if you're in /home/pi, it will look it up into /home/pi/home/pi/movestepper6.py and tell you the script does not exists. So the proper command should be:
alias runstepper='python /home/pi/mystepper6.py'
alias moveit='sudo python /home/pi/moveit.py'
Though as a suggestion to you, instead of making aliases to run python scripts, I'd make them into a proper python package. Considering that within both codes your entry points are a function called main(), i.e., both scripts end with:
if __name__ == "__main__":
main()
you should create a directory for your project:
cd /home/pi
# create a directory for your python project:
mkdir motion_control
# create a directory to place your scripts within:
mkdir motion_control/motion_control
# adding an empty __init__.py file makes that directory a python package
touch motion_control/motion_control/__init__.py
nano motion_control/setup.py
and now you just have to add this within the setup.py file:
from setuptools import setup
setup(name='motion_control',
version='0.1',
description="Python library to operate stuff that move on my rasppi",
long_description='explain how to use the tools installed by this package',
classifiers=[],
keywords='raspberrypi motion control',
author='YOU',
author_email='YOUR#EMAIL',
url='ANY URL YOU THINK IS RELEVANT',
license='MIT', # or any license you think is relevant
packages=['motion_control'],
zip_safe=False,
install_requires=[
# add here any tool that you need to install via pip
# to have this package working
'setuptools',
],
entry_points="""
# -*- Entry points: -*-
[console_scripts]
runstepper = motion_control.mystepper6:main
moveit = motion_control.moveit:main
""",
)
the entry_points part is very important, as it's telling python where to look for the first function to execute to have the script run. For example:
moveit = motion_control.moveit:main
means "look for the main() function within the moveit module in the motion_control package". So adapt accordingly! As a note: don't make that main() function take any parameter, but rather do the argument parsing within it (if you parses arguments).
and finally, to install it, all you need to do is:
cd motion_control
sudo python setup.py install
and you'll have runstepper and moveit installed in the same directory as your python executable.
HTH

How to send and execute current line of code in gedit to terminal using external tools?

I just switched from Mac to Ubuntu. I am writing R scripts using Gedit. When I was using R in Mac, I was able to send current line of code or a selection of code to terminal. However, I have no idea how to do such a thing now.
Note: I am not a Linux user, so you may have to spell it out for me.
This is what I am looking for . How is this done??
http://www.youtube.com/watch?v=4jJDkcEs5yw
I am also happy to see how other people achieve this using other text editors
A good way of doing this is to use external tools in gedit.
Do the following:
gedit -> Edit -> Preferences -> Plugins -> Check External Tools
Then:
gedit -> Tools -> Manage External Tools
Here:
Add a tool by clicking on the '+' button.
Name: Run line
Shortcut Key: Alt+L (or whatever you are comfortable with)
Save: Nothing
Input: Current Line
Output: Display in bottom pane
Put this code in the Edit section:
#! /usr/bin/env python
import sys
import commands
line = sys.stdin.read()
print commands.getoutput(line)
Name: Run select
Shortcut Key: Alt+B (or whatever you are comfortable with)
Save: Nothing
Input: Current selection
Output: Display in bottom pane
Put this code in the Edit section:
#! /usr/bin/env python
import sys
import commands
line = sys.stdin.read().replace("\r","")
print commands.getoutput(line)

Resources