Is there a way to access hardware directly in Python? - python

I want to learn about graphical libraries by myself and toy with them a bit. I built a small program that defines lines and shapes as lists of pixels, but I cannot find a way to access the screen directly so that I can display the points on the screen without any intermediate.
What I mean is that I do not want to use any prebuilt graphical library such as gnome, cocoa, etc. I usually use Python to code and my program uses Python, but I can also code and integrate C modules with it.
I am aware that accessing the screen hardware directly takes away the multiplatform side of Python, but I disregard it for the sake of learning. So: is there any way to access the hardware directly in Python, and if so, what is it?

No, Python isn't the best choice for this type of raw hardware access to the video card. I would recommend writing C in DOS. Well, actually, I don't recommend it. It's a horrible thing to do. But, it's how I learned to do it, and it's probably about as friendly as you are going to get for accessing hardware directly without any intermediate.
I say DOS rather than Linux or NT because neither of those will give you direct access to the video hardware without writing a driver. That means having to learn the whole driver API, and you need to invoke a lot of "magic," that won't be very obvious because writing a video driver in Windows NT is fairly complicated.
I say C rather than Python because it gives you real pointers, and the ability to do stupid things with them. Under DOS, you can write to arbitrary physical memory addresses in C, which seems to be what you want. Trying to get Python working at all under an OS terrible enough to allow you direct hardware access would be a frustration in itself, even if you only wanted to do simple stuff that Python is good at.
And, as others have said, don't expect to use anything that you learn with this project in the real world. It may be interesting, but if you tried to write a real application in this way, you'd promptly be shot by whoever would have to maintain your code.

This seems a great self-learning path and I would add my two-cents worth and suggest you consider looking at the GObject, Cairo and Pygame modules some time.
The Python GObject module may be at a higher level than your current interest, but it enables pixel level drawing with Cairo (see the home page) as well as providing a general base for portable GUI apps using Python
Pygame also has pixel level methods as well as access methods to the graphics drivers (at the higher level) - here is a quick code example

This is rather an old thread now, but I stumbled upon it while musing the same question.
I used to program in assembly language. In my day, drawing on screen was simply(?) a matter of poking a value into a memory location. The value turned a pixel on or off and defined its colour.
The term 'poke' comes from Basic by the way, not assembler. In assembler, you had to write a value into a data register then tell the processor where to put the data using another command and specifying an address register, usually in hexadecimal form! And each different processor had its own assembly language. But hec was the code fast!
As hardware progressed, I found that graphics hardware programming became more and more complex. There's much more to it than now simply defining a pixel. The graphics subsystem has its own processor -- or processors -- and it's that that you've got to learn to talk to. The processor doesn't just plonk stuff in memory locations. (I believe that what used to be the fastest supercomputer in the world for a while ran on graphics chips!) 'Plonk' is not a Basic command by the way.
Sorry; I digress. In answer to the original poster's query, I believe that the goal of understanding the graphics-drawing process could have been best achieved by experimenting with a Raspberry Pi. It's Python compatible and hence perfect for the job. Its hardware is well documented and it's cheap and easy to use.
Hope this helps someone, Cheers, M

Related

Manipulate an application window frame using Python

TLDR: Is there a Python library that allows me to get a application window frame as an image and rewrite it to the said application?
So the whole story is that I want to write an application using Python that does something similar to Lossless Scaling and Magpie. I want to grab an application window (a videogame window, for example), get the current frame as an image, then use some Machine Learning/Deep Learning algorithm (like FSR or DLSS) to upscale said image, then rewrite the current frame from the application with said upscaled image.
So far, I have been playing around with some upscaling algorithms like the one from Real-ESRGAN, but now my main problem is how to upscale the video game images in real-time. The only thing I found that does something related to what I need to do is PyAutoGUI. But this package only allows you to take screenshots of an application but not rewrite the graphics of said application.
I hope I have clarified my problem; feel free to comment if you still have any questions.
Thank you for reading this post, and have a good day.
Doing this with Python is going to be very difficult. A lot of the performance involved in this sort of thing is in avoiding as many memory copies as possible, and Python's idiom for string and bytes processing unfortunately makes quite a few additional copies in the course of any idiomatic program. I say this as a die-hard Python fan who is constantly trying to cram Python in everywhere it doesn't belong: you'd be better off doing this in Rust.
Update: After receiving some feedback from some folks with more direct experience in this sort of thing, I may have overstated the difficulty here. Many ML tools in Python provide zero-copy access, you can easily access and manipulate memory-mapped data from numpy and there is even a CUDA protocol for doing this to data in GPU memory, so while it's not exactly easy, as long as your operations are implemented as numpy operations and not as pure-python pixel-by-pixel logic, it shouldn't be much harder than other python machine learning applications which require access to native APIs for accessing their source data.
However, there's no way to access framebuffer data directly from python, so step 1 is going to be writing your own bindings over the relevant DirectX APIs. Since Magpie is open source, you can see which APIs it's using, for example, in its various C++ "Frame Source" backends. For example, this looks relevant: https://github.com/Blinue/Magpie/blob/42cfcba1222b07e4cec282eaff639aead229f123/Runtime/GraphicsCaptureFrameSource.cpp#L87
You can then look those APIs up on MSDN; that one, for example, is here: https://learn.microsoft.com/en-us/uwp/api/windows.graphics.capture.direct3d11captureframepool.createfreethreaded?view=winrt-22621
CFFI is a good choice for writing native wrappers: https://cffi.readthedocs.io/en/latest/
Gluing these together appropriately is left as an exercise for the reader :).

Python: creating a new window, accessing it's pixels and activating them

I have been thoroughly searching this forum, the internet, and pretty much everything. I want to be able to create a new graphics window in python without using something else, for a project in which I want specialized optimized for whatever a need without any other extra mumbo-jumbo, and understanding fully how it works. Anyways, I want to be able to access pixel by pixel of a new window without using tkinter/turtle, installations, or anything of the sort. Just basic, simple, pixel access of a new window. If this isn't possible, just let me know. I imagine the program could look something like this:
import NOTHING_AT_ALL_GRAPHICS_WISE
window.pixel(1,2,True)
I program in Python 3.6.3
What you seek to accomplish isn't as simple as you might believe. Applications draw graphics on the screen largely with the help of calls to the graphics card API. Those API's can be complicated, as they should be, because all the graphics that you see on your screen, whether it be your browser GUI, to video playback, to your Starcraft II, has to use combinations of these calls to produce the beautiful and seamless graphics you see on your screen (graphics would NOT look good without use of the GPU).
However, not all manipulation of graphics has to be so complicated, and many languages/frameworks write wrappers around some of the graphics libraries that expose a simpler subset of the total functionality. Tkinter is a good example.
If you don't want to import ANYTHING, you will have to make the calls to the API yourself, and you're not in for a good time. Nobody does this nowadays for personal projects because it really is quite complicated. Also, Python is a very high-level language, and although it might expose the OS's system calls that you need, you're probably better off doing it in C. Before you proceed, I suggest you read up on the fundamentals of computer graphics work. Here's a nice image that shows how OpenGL, a very popular graphics library, works.
There is no way to do what you want. Python has no way of changing a single pixel on the screen. This is the whole reason why such "mumbo jumbo" libraries exist: it's a complex problem that requires specialized libraries that know how each operating system works.

Audio Domain Specific Language vs Python

I want to write some code to do acoustic analysis and I'm trying to determine the proper tool(s) for the job. I would normally write something like this in Python using numpy and scipy and possibly Cython for the analysis part. I've discovered that the world of Python audio libraries is a bit chaotic, with scads of very limited packages in various states of development.
I've also come across a bunch of audio/acoustic specific languages like SuperCollider, Faust, etc. that seem to make the audio processing easy but may be limited in terms of IO and analysis capability.
I'm currently working on Linux with Alsa and PulseAudio installed by default. I would prefer not to involve and of the various and sundry other audio packages like Jack if possible, though that is not a hard requirement.
My primary interest in this question is to determine whether there is a domain specific language that will provide for quicker prototyping and testing or whether a general language like Python is more appropriate. Thanks.
I've got a lot of experience with SuperCollider and Python (with and without Numpy). I do a lot of audio analysis, and I'm afraid the answer depends on what you want to do.
If you want to create systems that will input OR output audio in real time, then Python is not a good choice. The audio I/O libraries (as you say) are a bit sketchy. There's also a fundamental issue that Python's garbage collector is not really designed for realtime stuff. You should use a system that is designed from the ground up for realtime. SuperCollider is nice for this, and as caseyanderson notes, some of the standard building-blocks for audio analysis are right there. There are other environments too.
If you want to do hardcore work such as applying various machine learning algorithms, not necessarily in real time (i.e. if you can get away with reading/writing WAV files rather than live audio), then you should use a general-purpose programming language with wide support, and an ecosystem of good libraries for the extra things you want. Using Python with libs such as numpy and scikits-learn works great for this. It's good for quick prototyping, but not only does it lack solid realtime audio, it also has far fewer of the standard audio building-blocks. Those are two important things which hold you back when prototyping audio pipelines.
So, then, you're caught between these two options. Depending on your application you may be able to combine the two by manipulating the audio I/O in a realtime environment, and using OSC messaging or shell scripts to communicate with an external Python process. The limitation there is that you can't really throw masses of data around between the two (you can't sensibly pipe all your audio across to some other process, that'd be silly).
SuperCollider has lots of support for things along these lines, both as externals/plugins or Quarks. That said, it depends exactly what you want to do. If you are simply looking to detect events, Onsets.kr would be fine. If you are looking for frequency/pitch information, Pitch or Tartini would work (I find Tartini to be more accurate). If you are trying to track amplitude, a combination of Amplitude.ar and some simple math would also work.
Similarly, there is SpecCentroid.kr (for a kind of brightness analysis), Loudness.kr, SpecFlatness.kr, etc.
The above are all pretty general, and there are lots more (the JoshUGens externals package has some interesting FFT-related acoustics stuff). So I would recommend downloading the program, joining the mailing list (if you have further questions), which lives here, and poking around in the Externals, Quarks, and Standard UGens.
Nonetheless, since I am not sure what you are trying to do, I cannot make more concrete recommendations than the above combined with my feeling that it makes the most sense to go to SC for this, rather than writing all of your own tools in Python from scratch.
I'm not 100% sure what you want to do, but as an additional suggestion I would put forth: Spear with scripting in Common Lisp. If what you are doing involves a great deal of spectral analysis, then you can do the heavy Lifting in Spear, and script all of this using Common List with Common Music. Spear has some great tools in terms of editing out very specific partials.

How to prevent decompilation or inspecting python code?

let us assume that there is a big, commercial project (a.k.a Project), which uses Python under the hood to manage plugins for configuring new control surfaces which can be attached and used by Project.
There was a small information leak, some part of the Project's Python API leaked to the public information and people were able to write Python scripts which were called by the underlying Python implementation as a part of Project's plugin loading mechanism.
Further on, using inspect module and raw __dict__ readings, people were able to find out a major part of Project's underlying Python implementation.
Is there a way to keep the Python secret codes secret?
Quick look at Python's documentation revealed a way to suppres a import of inspect module this way:
import sys
sys.modules['inspect'] = None
Does it solve the problem completely?
No, this does not solve the problem. Someone could just rename the inspect module to something else and import it.
What you're trying to do is not possible. The python interpreter must be able to take your bytecode and execute it. Someone will always be able to decompile the bytecode. They will always be able to produce an AST and view the flow of the code with variable and class names.
Note that this process can also be done with compiled language code; the difference there is that you will get assembly. Some tools can infer C structure from the assembly, but I don't have enough experience with that to comment on the details.
What specific piece of information are you trying to hide? Could you keep the algorithm server side and make your software into a client that touches your web service? Keeping the code on a machine you control is the only way to really keep control over the code. You can't hand someone a locked box, the keys to the box, and prevent them from opening the box when they have to open it in order to run it. This is the same reason DRM does not work.
All that being said, it's still possible to make it hard to reverse engineer, but it will never be impossible when the client has the executable.
There is no way to keep your application code an absolute secret.
Frankly, if a group of dedicated and determined hackers (in the good sense, not in the pejorative sense) can crack the PlayStation's code signing security model, then your app doesn't stand a chance. Once you put your app into the hands of someone outside your company, it can be reverse-engineered.
Now, if you want to put some effort into making it harder, you can compile your own embedded python executable, strip out unnecessary modules, obfuscate the compiled python bytecode and wrap it up in some malware rootkit that refuses to start your app if a debugger is running.
But you should really think about your business model. If you see the people who are passionate about your product as a threat, if you see those who are willing to put time and effort into customizing your product to personalize their experience as a danger, perhaps you need to re-think your approach to security. Assuming you're not in the DRM business, or have a similar model that involves squeezing money from reluctant consumers, consider developing an approach that involves sharing information with your users, and allowing them to collaboratively improve your product.
Is there a way to keep the Python secret codes secret?
No there is not.
Python is particularly easy to reverse engineer, but other languages, even compiled ones, are easy enough to reverse.
You cannot fully prevent reverse engineering of software - if it comes down to it, one can always analyze the assembler instructions your program consists of.
You can, however, significantly complicate the process, for example by messing with Python internals. However, before jumping to how to do it, I'd suggest you evaluate whether to do it. It's usually harder to "steal" your code (one needs to fully understand them to be able to extend them, after all) than code it oneself. A pure, unobfuscated Python plugin interface, however, can be vital in creating a whole ecosystem around your program, far outweighing the possible downsides to having someone peek in your maybe not perfectly designed coding internals.

What are the downsides of using Python instead of Objective-C? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the lingua franca for Mac OS X development (which means it has better documentation).
I'm thinking about starting Mac development - will using PyObjC+Python make me a second class citizen?
Yes.
For one thing, as you note, all the documentation is written for Objective-C, which is a very different language.
One difference is method name. In Objective-C, when you send a message to (Python would say “call a method of”) an object, the method name (selector) and arguments are mixed:
NSURL *URL = /*…*/;
NSError *error = nil;
QTMovie *movie = [QTMovie movieWithURL:URL
error:&error];
This isn't possible in Python. Python's keyword arguments don't count as part of the method name, so if you did this:
movie = QTMovie.movieWithURL(URL, error = ???)
you would get an exception, because the QTMovie class has no method named movieWithURL; the message in the Objective-C example uses the selector movieWithURL:error:. movieWithURL: and movieWithURL would be two other selectors.
There's no way they can change this, because Python's keyword arguments aren't ordered. Suppose you have a hypothetical three-argument method:
foo = Foo.foo(fred, bar=bar, baz=baz)
Now, this calls foo:bar:baz:, right?
Not so fast. Foo may also have a method named foo:baz:bar:. Because Python's keyword arguments aren't ordered, you may actually be calling that method. Likewise, if you tried to call foo:baz:bar:, you may actually end up calling foo:bar:baz:. In reality, this case is unlikely, but if it ever happens, you would be unable to reliably call either method.
So, in PyObjC, you would need to call the method like this:
movie = QTMovie.movieWithURL_error_(URL, ???)
You may be wondering about the ???. C doesn't allow multiple return values, so, in Objective-C, the error: argument takes a pointer to a pointer variable, and the method will store an object in that variable (this is called return-by-reference). Python doesn't have pointers, so the way the bridge handles arguments like this is that you pass None, and the method will (appear to) return a tuple. So the correct example is:
movie, error = QTMovie.movieWithURL_error_(URL, None)
You can see how even a simple example deviates from what documentation might show you in Objective-C.
There are other issues, such as the GIL. Cocoa apps are only going to get more concurrent, and you're going to want in on this, especially with tempting classes like NSOperation lying around. And the GIL is a serious liability, especially on multi-core machines. I say this as a Python guy myself (when not writing for Cocoa). As David Beazley demonstrates in that video, it's a cold, hard fact; there's no denying it.
So, if I were going to switch away from Objective-C for my apps, I would take up MacRuby. Unlike with PyObjC and RubyCocoa, messages to Cocoa objects don't cross the language bridge; it's a from-the-ground-up Ruby implementation in Cocoa, with language extensions to better support writing Cocoa code in it.
But that's too far ahead of you. You're just getting started. Start with Objective-C. Better to avoid all impedance mismatches between the language you're using and the one the documentation is written for by keeping them the same language.
Plus, you'll find some bugs (such as messages to deceased objects) harder to diagnose without knowledge of how Objective-C works. You will write these bugs as a new Cocoa programmer, regardless of which language you're writing the code in.
So, learn C, then learn Objective-C. A working knowledge of both shouldn't take more than a few weeks, and at the end of it, you'll be better prepared for everything else.
I won't go into how I learned C; suffice to say that I do not recommend the way I did it. I've heard that this book is good, but I've never owned nor read it. I do have this book, and can confirm that it's good, but it's also not Mac-specific; skip the chapter on how to compile the code, and use Xcode instead.
As for Objective-C: The Hillegass book is the most popular, but I didn't use it. (I have skimmed it, and it looks good.) I read Apple's document on the language, then jumped right in to writing small Cocoa apps. I read some of the guides, with mixed results. There is a Currency Converter tutorial, but it didn't help me at all, and doesn't quite reflect a modern Cocoa app. (Modern apps still use outlets and actions, but also Bindings, and a realistic Currency Converter would be almost entirely a couple of Bindings.)
This really says it all:
As the maintainer of PyObjC for nearly
15 years, I will say it bluntly. Use
Objective-C. You will need to know
Objective-C to really understand Cocoa
anyway and PyObjC is just going to add
a layer of bugs & issues that are
alien to 99% of Cocoa programmers.
a comment in an answer to this question. This question is also interesting.
DO NOT ATTEMPT to avoid learning objective-C if you're going to write apps for the Mac. The purpose of PyObjC and the other language bindings is to let you re-use existing libraries in your apps, not to let you avoid learning the native tools.
Second class citizen seems a bit strong. The Objective-C API's are available from Python as well, should you need them, and that's mostly if you want to make Cocoa apps. But then they are restricted to OS X anyway. Personally, I have no interest in building apps that isn't cross-platform, but that's me. That also means I haven't actually done this, so I don't know how tricky it is, but there was an article in the Python Magazine not long ago, and it didn't look that horrible.
The major drawback of Python is execution time, and that mainly comes from it being a dynamic language. This can be solved with Cython and C-extensions, etc, but then you get a mix of Python + ObjectiveC API's + Cython which can be daunting.
So it depends a lot of what kinds of applications you are going to make. Something uniquely OSX-ish that makes no sense anywhere else? ObjectiveC is probably the ticket. Cross-platform servers, well then Python rocks! Something else? Then it depends.
This is something I've been wondering myself, and although I hope someone comes by with more experience, from what I know you will not be seriously constrained by Python itself. Along with Java and GCC, Python is an excellent way to write native cross-platform applications. Once you get the hang of it you should be able to map example code in Objective C to your Python code.
Since you have access to all libraries and events, everything that you can do in Objective C will be there in Python. Of course, the more OS X-only calls and functions you use, the less easy it will be to port to another platform, but that's beside the point. Usually graphics programming and working with device drivers is somewhat of a limiting factor - but in both cases I'm finding evidence of good support and community libraries (search for Python and Quartz, Lightblue, libhid, PyUSB, for some examples).
The decisive factor for me would be: what is the level of tooling and IDE support that is needed. Apple provides some great software for building new software, but then again with something like Pydev you've got a great place to write Python code too! http://pydev.org/
So give it a try, I'm sure you won't regret it, and there will be a supportive community to draw on for help and insipiration.
You're going to need Objective-C: that's what all the tutorials, documentation, sample code, and everything is written in. In addition to a wilder variety of people being able to help you.
So learn ObjC first. If, on your second or third project, or a year down the road, you start a project that needs a Python module (like, say, Twisted, or SQLAlchemy. But a SERIOUS need like foundation of your app need, where the extra boost your app gets makes everything worth it), then you can write a PyObjC app and get a lot of the speed benefits of that language, with your background in Cocoa.
Just as an extra option, consider that wxPython can produce some pretty good applications on Mac as well as on Linux and Windows. For the most part you can get native appearance but maintain portability with little or no attention to platform-specific issues.
In other words, PyObjC + Python is not the only way to do Mac development with Python.
No you dont need to know Objective C you dont need to use PyObjC , and you wont be a second class citizent.
Unless you want to do something extremely specific to the MAC platform , coding in Objective C or using PyObjC is a really bad idea.
The reason is obvious, once you go the objc route you say a big "goodbye" to other platforms. Its that simple.
Apple does not want you to code for other platforms the same way Microsoft does not want you to code for other platforms. And that is why more and more developers are turning to open source languages like, python, java, ruby etc. Because you dont care what Apple and Microsot , you only care about an App that is the most useful and most easy to develop. And making your App available only for MAC will make it less useful and obviously developing in Objective C is way more difficult.
Python has more than enough libraries to accomodate you , hundrends of them , readily available for the mac platform. I for instance develope a new application in pygame, no its not a game, if I have done the same thing in ObjC or PyObj I would have to rewrite the code for windows and linux. While with pygame my code works exactly the same in windows and linux even though my main platform is macos.
Thats the appeal of most python libraries , they are cross platform. WxPython is another example, someone mentioned that "it does not exactly look natively" , do you want this to stop you from making your application available for windows and linux. Why limit yourself only on the MAC platform ? Do you think the average user will care how natively your app will look. Even macos apps do not look native , many of them introduce their own "eye candy" gui. Not that you cant make WxPython look 100% native, the way you code is always importnat.
Objc makes sense when you intend to develop for Iphone OS , as Apple thought it a great idea to exclude python (and not only python), even though they were forced to include javascript (or else websurfing would have being a nightmare on iphoneos) . Pyjamas, can make python available for iphone os as well (with no hacks or jailbroken phones), but with the obvious limitations since it translates python code to javascript, but still its a valid solution till Apple decide that excluding python from iphone os is a really bad idea.
link text
There is no harm done in studying Objective C though. You can always use the native libraries via pyobjc.
But to be absolutely sincere with you, If my app reaches a dead end with the python libraries ( a very unlikely scenario) I would rather wrap an existing cross platform C/C++ Libraries with Cython than go the objective c pyobjc route and detroy the cross platform ability of my app. The last thing I would be using is anything platoform specifc.
Now if you dont care about other platforms at all, then I guess Objective C can be a valid choice. It certainly looks ugly as hell, but I have heard that it gets much better the more you use it and there are many people that prefer it over C/C++.

Categories