How to enable other programs to modify existing program - python

I am in the works of creating a python program similar to this
. Anyway what i want to do is have users be able to modify there own programs but i need help understanding how this works. I have looked through the source code and am confused where this happens even if someone could just point me towards that that would be very helpful. I know that the programs will not be sandboxed but that is not something im worried about at the moment. If you could point me in any direction that would be great! Thank you!

The "robot programs" are just stored as plain text files.
There's a general-purpose text editor in editor.py. When you open a robot in a given view, e.g., the Qt4 view in qt4view.py, it just instantiates a text editor and hands it the robot's file. Again, the fact that the robot's file is a Python script doesn't matter; it just edits it as a text file.
The battle code, meanwhile, opens the same robot files as Python code that the text editor opens as text files. You can see this code in game.py: It just uses the subprocess module to run Python, passing the robot file as an argument.

My other answer deals with what you actually asked. But I don't think it's what you really wanted to know.
You just want to know how to run some Python script, that you've got a pathname for, in a separate Python interpreter, right?
While it's possible to figure that out from the pybotwar code, there's a whole lot of extra stuff that will get in the way of understanding it—the conf.py file, the configurable extra flags, etc.
But the answer is simple: Use the subprocess module, just as you would for running any program. In this case, the Python interpreter is the executable (usually you want sys.executable, the same Python interpreter you're using), and the script you want to run as an argument. For example:
script_output = subprocess.check_output([sys.executable, script_path])
The subprocess documentation explains all the different options very nicely.

Related

ANSI escape codes not working on IDLE... (python)

I am making a program involving ANSI escape codes, and they were all working fine on replit until I switched back to IDLE (3.9 on both). But it doesn't work:
it should have looked like this:
I have seen several posts before that complain that the IDLE doesn't support these escape sequences because it isn't a terminal, so I tried to do it directly from the cmd but the beastly symbol still appeared, this time as a boxed question mark:
I know that it won't work straight from the IDLE, so I wonder if you can import a software like mintty into python?
Powershell works though...
P.S. please don't tell me to import colorama or something! I really want this to be the way. I also don't have immediate access to iPython (even though I would like to) so it's not really an option for me... unless I have to :D
EDIT: the code I put across the python programs:
import sys, os
os.system("")
CSI = f"{chr(0x1B)}["
print(f"""{CSI}3m{CSI}1m{CSI}4m{CSI}31m
look at this""")
sys.stdout.flush()
# I put the sys.stdout.flush() and os.system("") to try and fix the problem...
The IDLE shell is not a terminal emulator and not intended to be production environment. The decision so far is that is should show program developers what their program's output, without interpretation. This may change in the future but no final decision yet.
If you are on Windows, I believe its console can be put into ANSI mode, but Python does not do that for you. I don't know if program code can do so.
As near as I can tell, there is not wrapper program that turns mintty into an importable python module. It would not make much sense. Rather, you would want to open mintty or a mintty-based terminal-emulator, such as git bash, and open python within that terminal instead of CommandPrompt.
ANSI code is a broad term. You have to specify which code page you are using. For example, my Windows is in Chinese Simplified. Therefore if I want to escape from UTF-8 default in Python, I would put # coding : cp936 on the first or second line of a script. Then it can read and write text files with the simplified Chinese coding.
Second Question:
Could I make a red/green/etc. font for every character and put it as print('...', file=...)? It should be possible because colored emojis exist.
It should work, but I would like to know how I could (if it's possible) automate this with some program that makes a file containing those characters and displays them with the previous print statement.
Cheers!

Maya Python creating a script with a script

I've got a kind of weird question--but would be immensely useful if it is possible--in Maya using Python, can I take in several points of user input and have Python create a separate script for me? In this instance, I want to take in controller and locator names and have Python spit out a complete IKFK match script also in Python (it's really just a lot of getAttr and setAttr commands, although with 6 if statements per limb for PV matching.) The only other wrinkle there is that it has to be able to prefix hierarchy names in the script if necessary if the rig is imported into a new scene rather than just opened. There's an expression component to my switches that it would be nice if Python could make for me, too.
Is this possible or am I crazy?
That's no problem. Just write a textfile with a .py extension into a path where maya can find it. Then you have to import it somewhere. Creating expressions is not a problem either.
Maybe it could make sense to think about the approach you choose. Imagine you have written a dozen of these new python files and you discover a problem in the script, you will have to redo it. I'd try to collect all data and only write the required informations into a textfile e.g. in json format. Then you can read the data and rebuild your skeletons.

getting list of camera or render globals from maya scene file without opening scene in maya

is it possible with python to read a maya scene file without opening and get list of camera's or render globals setting or perform some operations on it.
I need this so that if their are multiple scene files I do not have to open each maya scene and just tweak it from a python script, I would really appreciate if some one can show how to start rest I will do myself...
Its possible, may just not be practical. A Maya ASCII file is pretty trivial to parse. A Maya binary file not so much. It may be a bit premature to discuss there matters.
First things first. Maya does offer a batch mode, the batch mode does not use up a full license. It still opens a full Maya environment but no GUI. This is the perfect platform to inject scripts. It doesn't really fulfill your request of not opening Maya but it fulfills all other requirements. There are a few ways for using this batch mode. But mostly it boils down to two general methods.
Method 1, using mayabatch: The mayaXX/bin/ directory contains a command called mayabatch. You can simply call this from a cmd/shell batch file/shellscript. This is a extremely simple way of calling existing scripts. Assuming mayabatch is in the path of your environment and your script is in Maya script path. Lets assume for simplicity that your script looks as follows (demo.py):
import maya.cmds as cmd
def func():
print cmd.ls()
# we want this to execute on import
func()
Now calling this for one file under windows would look as following:
mayabatch -command "python(""import demo"") " -file filename.ma
calling this over all Maya in the current folder files would then be simply:
for %i in (*.ma) do mayabatch -command "python(""import demo"") " -file %i
The quoting rules are a bit different on mac and Linux but should be easy to find. reefer to the manual of your shell.
Method 2, using mayapy and standalone:
Now you can also directly call the python script with mayapy. Its located in the same directory as mayabtach. Tough the standalone can be called form other python interpreters too if you include Maya modules in the system path. Now the script must be a bit changed so it does the same thing (demo_direct.py):
#init maya
import maya.standalone
maya.standalone.initialize( name='python' )
import maya.cmds as cmd
import glob
def func():
print cmd.ls(shapes=True)
for file in glob.glob('*.m[ab]'):
cmd.file( file, o=True )
func()
call this form command line with:
mayapy demo_driect.py
Neither of these methods load Mayas graphical user interface. So you can not call stuff like playblast etc. Since they rely on a GUI, and thus a full Maya license. Nothing says you can not do a similar load loop in the GUI as above.
Then for the methods without actually loading Maya. This is a bit tricky. Doing this is not necessarily worth it since the batch nodes are pretty fast as they don't eventuate everything on load. A sample script that parses a Maya ASCII file for frame ranges. You might find it useful. See following post. For Maya binary files there is a python module in cgKit that will help you read Maya binary chunks. Unfortunately it doesn't do anything for understanding the data.

Start Another Program From Python >Separately<

I'm trying to run an external, separate program from Python. It wouldn't be a problem normally, but the program is a game, and has a Python interpreter built into it. When I use subprocess.Popen, it starts the separate program, but does so under the original program's Python instance, so that they share the first Python console. I can end the first program fine, but I would rather have separate consoles (mainly because I have the console start off hidden, but it gets shown when I start the program from Python with subprocess.POpen).
I would like it if I could start the second program wholly on its own, as though I just 'double-clicked on it'. Also, os.system won't work because I'm aiming for cross-platform compatibility, and that's only available on Windows.
I would like it if I could start the second program wholly on its own, as though I just 'double-clicked on it'.
As of 2.7 and 3.3, Python doesn't have a cross-platform way to do this. A new shutil.open method may be added in the future (possibly not under that name); see http://bugs.python.org/issue3177 for details. But until then, you'll have to write your own code for each platform you care about.
Fortunately, what you're trying to do is simpler and less general than what shutil.open is ultimately hoped to provide, which means it's not that hard to code:
On OS X, there's a command called open that does exactly what you want: "The open command opens a file (or a directory or URL), just as if you had double-clicked the file's icon." So, you can just popen open /Applications/MyGame.app.
On Windows, the equivalent command is start, but unfortunately, that's part of the cmd.exe shell rather than a standalone program. Fortunately, Python comes with a function os.startfile that does the same thing, so just os.startfile(r'C:\Program Files\MyGame\MyGame.exe').
On FreeDesktop-compatible *nix systems (which includes most modern linux distros, etc.), there's a very similar command called xdg-open: "xdg-open opens a file or URL in the user's preferred application." Again, just popen xdg-open /usr/local/bin/mygame.
If you expect to run on other platforms, you'll need to do a bit of research to find the best equivalent. Otherwise, for anything besides Mac and Windows, I'd just try to popen xdg-open, and throw an error if that fails.
See http://pastebin.com/XVp46f7X for an (untested) example.
Note that this will only work to run something that actually can be double-clicked to launch in Finder/Explorer/Nautilus/etc. For example, if you try to launch './script.py', depending on your settings, it may just fire up a text editor with your script in it.
Also, on OS X, you want to run the .app bundle, not the UNIX executable inside it. (In some cases, launching a UNIX executable—whether inside an .app bundle or standalone—may work, but don't count on it.)
Also, keep in mind that launching a program this way is not the same as running it from the command line—in particular, it will inherit its environment, current directory/drive, etc. from the Windows/Launch Services/GNOME/KDE/etc. session, not from your terminal session. If you need more control over the child process, you will need to look at the documentation for open, xdg-open, and os.startfile and/or come up with a different solution.
Finally, just because open/xdg-open/os.startfile succeeds doesn't actually mean that the game started up properly. For example, if it launches and then crashes before it can even create a window, it'll still look like success to you.
You may want to look around PyPI for libraries that do what you want. http://pypi.python.org/pypi/desktop looks like a possibility.
Or you could look through the patches in issue 3177, and pick the one you like best. As far as I know, they're all pure Python, and you can easily just drop the added function in your own module instead of in os or shutil.
As a quick hack, you may be able to (ab)use webbrowser.open. "Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable." In particular, IIRC, it will not work on OS X 10.5+. However, I believe that making a file: URL out of the filename actually does work on OS X and Windows, and also works on linux for most, but not all, configurations. If so, it may be good enough for a quick&dirty script. Just keep in mind that it's not documented to work, it may break for some of your users, it may break in the future, and it's explicitly considered abuse by the Python developers, so I wouldn't count on it for anything more serious. And it will have the same problems launching 'script.py' or 'Foo.app/Contents/MacOS/foo', passing env variables, etc. as the more correct method above.
Almost everything else in your question is both irrelevant and wrong:
It wouldn't be a problem normally, but the program is a game, and has a Python interpreter built into it.
That doesn't matter. If the game were writing to stdout from C code, it would do the exact same thing.
When I use subprocess.Popen, it starts the separate program, but does so under the original program's Python instance
No it doesn't. It starts an entirely new process, whose embedded Python interpreter is an entirely new instance of Python. You can verify that by, e.g., running a different version of Python than the game embeds.
so that they share the first Python console.
No they don't. They may share the same tty/cmd window, but that's not the same thing.
I can end the first program fine, but I would rather have separate consoles (mainly because I have the console start off hidden, but it gets shown when I start the program from Python with subprocess.POpen).
You could always pipe the child's stdout and stderr to, e.g., a logfile, which you could then view separately from the parent process's output, if you wanted to. But I think this is going off on a tangent that has nothing to do with what you actually care about.
Also, os.system won't work because I'm aiming for cross-platform compatibility, and that's only available on Windows.
Wrong; os.system is available on "Unix, Windows"--which is probably everywhere you care about. However, it won't work because it runs the child program in a subshell of your script, using the same tty. (And it's got lots of other problems—e.g., blocking until the child finishes.)
When I use subprocess.Popen, it starts the separate program, but does so under the original program's Python instance...
Incorrect.
... so that they share the first Python console.
This is the crux of your problem. If you want it to run in another console then you must run another console and tell it to run your program instead.
... I'm aiming for cross-platform compatibility ...
Sorry, there's no cross-platform way to do it. You'll need to run the console/terminal appropriate for the platform.

Python file read problem

file_read = open("/var/www/rajaneesh/file/_config.php", "r")
contents = file_read.read()
print contents
file_read.close()
The output is empty, but in that file all contents are there. Please help me how to do read and replace a string in __conifg.php.
Usually, when there is such kind of issues, it is very useful to start the interactive shell and analyze all commands.
For instance, it could be that the file does not exists (see comment from freiksenet) or you do not have privileges to it, or it is locked by another process.
If you execute the script in some system (like a web server, as the path could suggest), the exception could go to a log - or simply be swallowed by other components in the system.
On the contrary, if you execute it in the interactive shell, you can immediately see what the problem was, and eventually inspect the object (by using help(), dir() or the module inspect). By the way, this is also a good method for developing a script - just by tinkering around with the concept in the shell, then putting altogether.
While we are here, I strongly suggest you usage of IPython. It is an evolution of the standard shell, with powerful aids for introspection (just press tab, or a put a question mark after an object). Unfortunately in the latest weeks the site is not often not available, but there are good chances you already have it installed on your system.
I copied your code onto my own system, and changed the filename so that it works on my system. Also, I changed the indenting (putting everything at the same level) from what shows in your question. With those changes, the code worked fine.
Thus, I think it's something else specific to your system that we probably cannot solve here (easily).
Would it be possible that you don't have read access to the file you are trying to open?

Categories

Resources