So I'm messing around with the "cmd" module for python, I want a command where you can type "python" and then it opens a python command line. Sort of like how an actual command line would.
Here's my current code.
import cmd
class pythonCmd(cmd.Cmd):
def do_(self, args): # <--- I want this command to have it so you don't type a key word
exec(args)
class cmdLine(cmd.Cmd):
def do_python(self, args):
prompt = pythonCmd()
prompt.prompt = 'python> '
prompt.cmdloop('Python 3.8.2')
prompt = cmdLine()
prompt.prompt = '> '
prompt.cmdloop('Command line starting . . .')
I don't know whether you have to use cmd module or not. But there are much better modules similar to cmd. Modules such as subprocess, os and etc.
I recently used subprocess module, try it.
How about this:
Instead of running your program that opens a shell that can take both python commands and potentially your own commands,
Run python shell, import your program module- you have native python shell that can run python code.
Add support of additional commands by implementing a function like cmd(args) which you can call from the shell. You may need to work on your module to simplify using it in interactive python shell by providing #aliases”to existing functions etc..
With do_shell function you can use it with "!" syntax. For example
> !print("Henlo world")
This would print it, you can use other commands too.
Related
I have a Python script that executes an apple script. I'd like to print to terminal from within the apple script.
Here is my Python code.
import applescript
myfunction = """
do shell script "echo " & "words to terminal"
"""
def runfunction():
applescript.tell.app("Terminal", myfunction, background = False)
And then I execute this with python -c 'import myapplescript; print myapplescript.runfunction()'
I've tried to print to terminal from within the apple script using the "do shell script" phrase and also copy "Hello World!" to stdout
import applescript
That is not a very good library. If your needs are simple, I would just use subprocess directly.
Also be aware that osascript is limited in its own IO support. There’s no built-in way to access stdin, and the only data that gets written to stdout is the last value (if any) returned at the end of the script. (You can write to stderr at any time using the log command, though that will have its own set of issues.)
If you want to access stdin/stdout directly in your AppleScript code, you’ll have to use Cocoa’s NSFileHandle class. I wrote a File library some years back that provided easy-to-use wrappers around that, though I don’t maintain or support it.
If your needs are more advanced—e.g. you want to call one or more AppleScript handlers or pass anything more complex than simple (short) strings—and you have PyObjC installed, you’d be better using [this library] (https://pypi.org/project/py-applescript/) or the AppleScript-ObjC bridge.
Running into issues executing a PowerShell script from within Python.
The Python itself is simple, but it seems to be passing in \n when invoked and errors out.
['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL
This is the code in full:
import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]
print command #<--- this is where I see the \n.
#\n does not appear when I simply 'print script'
So I have two questions:
How do I correctly store the script as a variable without writing to disk while avoiding \n?
What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?
How do I correctly store the script as a variable without writing to disk while avoiding \n?
This question is essentially a duplicate of this one. With your example it would be okay to simply remove the newlines. A safer option would be to replace them with semicolons.
script = fetch.read().replace('\n', ';')
What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?
Your command must be passed as an array. Also you cannot run a sequence of PowerShell statements via the -File parameter. Use -Command instead:
rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
I believe this is happening because you are opening up PowerShell and it is automatically formatting it a specific way.
You could possibly do a for loop that goes through the command output and print without a /n.
I am looking for a way to execute multiple commands in the same shell instance using a separate function for each, something that I can define when the shell process opens/closes and can pass commands to.
so far all the answers I have found have only been in a single function
ie:
#!/usr/bin/env python
from subprocess import check_call
check_call(r"""set -e
ls -l
<some command> # This will change the present working directory
launchMyApp""", shell=True)
I need the same effect but with each command in a different function like
shell.open()
shell.exec("dir")
shell.exec("cd C:/Users/" + User + "/Desktop)
shell.close()
if you are wondering whyyy it has to be separate the command to run is coming from user input. yes I realize that is a security risk, but security isn't a problem in this case, as its purely an educational venture and not going to be used for anything
you could use subprocess.check_call(cmds_str, shell=True) in conjunction with multiple commands in the same line: How to run two commands in one line in Windows CMD?
You could build each command individually and add them to a list, and then use ' & '.join(cmd_list) to get cmds_str.
I don't use Windows but it works on Linux.
You can try pexpect with cmd.exe
import pexpect
child = pexpect.spawn("cmd.exe")
child.expect_exact("> ")
#print(child.before.decode('utf-8'))
print(child.before)
child.sendline("dir")
child.expect_exact("> ")
print(child.before)
child.sendline("cd C:/Users/" + User + "/Desktop")
child.expect_exact("> ")
print(child.before)
It runs cmd.exe, sends command in child.sendline() and looks for prompt child.expect_exact("> ") to get all text generated by command child.before.
my problem might be very easy for some experienced python programmers (I'm not one of them).
I'm trying to start a server with an argument.
Currently i'm doing:
def startServer(host):
host.cmd( 'python server.py &' )
Is there a way to pass an argument to server.py?
def startServer(host):
host.cmd( 'python server.py an_argument_to_server &' )
is that really what you are looking for?
In order to run python run server.py from the command line, we can use the subprocess module. Documentation can be found here: https://docs.python.org/2/library/subprocess.html.
import subprocess
def startServer(host, argument):
subprocess.call(['python', 'server.py', argument])
When you call the startServer function with some argument (say an_argument_to_server), it will run python server.py an_argument_to_server in command line. We don't need the & character, as subprocess will automatically run in the background. The subprocess module also works for python 3.x
I am new to Python & Eclipse, and having some difficulties understanding how to pass command line argument to script running within Eclipse(Pydev).
The following link explains how to pass command line argument to python script.
To pass command line argument to module argecho.py(code from link above),
#argecho.py
import sys
for arg in sys.argv: 1
print arg
I would need to type into python console
[you#localhost py]$ python argecho.py
argecho.py
or
[you#localhost py]$ python argecho.py abc def
argecho.py
abc
def
How would I pass same arguments to Python script within Eclipse(Pydev) ???
Thanks !
Click on the play button down arrow in the tool bar -> run configurations -> (double click) Python Run -> Arguments tab on the right hand side.
From there you can fill out the Program Arguments text box:
If you want your program to ask for arguments interactively, then they cease to be commandline arguments, as such. However you could do it something like this (for debugging only!), which will allow you to interactively enter values that the program will see as command line arguments.
import sys
sys.argv = raw_input('Enter command line arguments: ').split()
#Rest of the program here
Note that Andrew's way of doing things is much better. Also, if you are using python 3.*, it should be input instead of raw_input,
Select "Properties" -->> "Run/Debug Settings".
Select the related file in right panel and then click on "Edit" button. It will open properties of selected file. There's an "Arguments" tab.
Years later, and not Eclipse,
but a variant of other answers to run my.py M=11 N=None ... in sh or IPython:
import sys
# parameters --
M = 10
N = 20
...
# to change these params in sh or ipython, run this.py M=11 N=None ...
for arg in sys.argv[1:]:
exec( arg )
...
myfunc( M, N ... )
See One-line-arg-parse-for-flexible-testing-in-python
under gist.github.com/denis-bz .
What I do is:
Open the project in debug perspective.
In the console, whenever the debugger breaks at breakpoint, you can type python command in the "console" and hit return (or enter).
There is no ">>" symbol, so it is hard to discover.
But I wonder why eclipse doesn't have a python shell :(