How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?

后端 未结 9 1425
生来不讨喜
生来不讨喜 2020-12-25 13:34

I\'m a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming

相关标签:
9条回答
  • 2020-12-25 14:36

    If you know your way around Apache this should get your started.

    0 讨论(0)
  • 2020-12-25 14:38

    This simple approach requires nothing except Python standard library. Create this directory structure:

    .
    |-- cgi-bin
    |   `-- script.py
    |-- index.html
    `-- server.py
    

    You put your scripts in "cgi-bin" directory, "index.html" contains links to scripts in "cgi-bin" directory (so you don't have to type them manually, although you could), and "server.py" contains this:

    import CGIHTTPServer
    CGIHTTPServer.test()
    

    To run your server, just run "server.py". That's it, no Apache, no other dependencies.

    HTH...

    0 讨论(0)
  • 2020-12-25 14:40

    A simple cgi script (or set of scripts) is all you need to get started. The other answers have covered how to do this so I won't repeat it; instead, I will stress that using plain text will get you a long way. Just output the header (print("Content-type: text/plain\n") plus print adds its own newline to give you the needed blank line) and then run your normal program.

    This way, any normal output from your script gets sent to the browser and you don't have to worry about HTML, escaping, frameworks, anything. "Do the simplest thing that could possibly work."

    This is especially appropriate for non-interactive private administrative tasks like you describe, and lets you use identical programs from a shell with a minimum of fuss. Your driver, the page with the buttons, can be a static HTML file with single-button forms. Or even a list of links.

    To advance from there, look at the logging module (for example, sending INFO messages to the browser but not the command line, or easily categorizing messages by using different loggers, by configuring your handlers), and then start to consider template engines and frameworks.

    Don't output your own HTML and skip to using one of the many existing libraries—it'll save a ton of headache even spending a bit of extra time to learn the library. Or at the very least encapsulate your output by effectively writing your own mini-engine.

    0 讨论(0)
提交回复
热议问题