Send commands to the opened python terminal - python

The goal is to open python terminal with pre-execution of some commands. In real life it's loading some modules and defines some variables, but here is a simplified version:
from subprocess import Popen, CREATE_NEW_CONSOLE
r=Popen("python",creationflags=CREATE_NEW_CONSOLE)
r.communicate(input=b"print(2+2)")
CREATE_NEW_CONSOLE is used, because otherwise terminal window doesn't appear (I run the code from IDE). The code above opens a python terminal window, but input doesn't get there. Trying some variations stops window from appearing, like:
r=Popen(["python","print(2+2)"],creationflags=CREATE_NEW_CONSOLE)
Or
r=Popen("python",creationflags=CREATE_NEW_CONSOLE, stdin=PIPE)
r.communicate(input=b"print(2+2)")
So what can be done to solve the problem?

this is what the environmental variable PYTHONSTARTUP is for...
see: https://docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP
another option would be to use the -c -i switches
C:\>python -i -c "x = 2+2;y=3+3"
>>> x
4
>>> y
6
>>>

Related

Vscode not interactive with python. Mac M1 chip

I am on a Mac with M1 chip and I have a problem with my VScode and python. It stays stuck on the ZSH shell even when I type the command to switch to bash (chsh -s /bin/bash). Lets say I run a simple code:
import cowsay
import sys
if len(sys.argv) == 2:
cowsay.cow("Hello, " + sys.argv[1])
I am supposed to be able to type my name in the shell after my python file name and it should print the cow saying Hello, Noah.
When I do so ((base) noahhaitas#Noahs-Mac-mini ~ % python3 itunes.py Noah Haitas), this is what I get as a message in my shell:
(base) noahhaitas#Noahs-Mac-mini ~ % python3 itunes.py Noah Haitas
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3: can't open file '/Users/noahhaitas/itunes.py': [Errno 2] No such file or directory
I am trying to figure out how I can switch fully to bash and have the $ in front instead of seeing the % of ZSH.
What can be done as this is frustrating and I looked everywhere online and tried pretty much every solution.
Vscode is just an editor, and the system terminal is still applied.
Use the following command in the terminal to switch bash and restart the terminal:
chsh -s /bin/bash
At the same time, you can also set manually in the vscode terminal. Take Windows as an example:
Read the docs for more details about terminal settings.
By the way, there is an error when you run the file. It seems that the python file is not run in the correct directory.

execute command in gnome-terminal using python

I am trying to open one file from gnome-terminal using python. But I am not able to do it.It is just opening terminal and not opening file.
I have tried like:
import os
os.system('gnome-terminal --working-directory = "folder_path" + "[-e, --command=" kate aaa.txt""')
Can anyone please help?
The problem is + "[-e, --command=" kate aaa.txt"", gnome-terminal doesn't know how to parse this + "[ and "", according to the manual, -e and --command mean the same thing:
man gnome-terminal
...
--command, -e=COMMAND
Split the argument to this option into a program and arguments in the same way a shell
would, and execute the resulting command-line inside the terminal.
This option is deprecated. Instead, use -- to terminate the options, and put the program
and arguments to execute after it: for example, instead of gnome-terminal -e "python3 -q",
prefer to use gnome-terminal -- python3 -q.
Note that the COMMAND is not run via a shell: it is split into words and executed as a
program. If shell syntax is required, use the form gnome-terminal -- sh -c '...'.
This works for me in Archlinux:
import os
os.system('gnome-terminal --working-directory = /home/ramsay --command="kate
os"')

Open new gnome-terminal and run command

I'm trying to write a script that opens a new terminal then runs a separate python script from that terminal.
I've tried:
os.system("gnome-terminal 'python f.py'")
and
p = Popen("/usr/bin/gnome-terminal", stdin=PIPE)
p.communicate("python f.py")
but both methods only open a new terminal and do not run f.py. How would I go about opening the terminal AND running a separate script?
Edit:
I would like to open a new terminal window because f.py is a simply server that is running serve_forever(). I'd like the original terminal window to stay "free" to run other commands.
Like most terminals, gnome terminal needs options to execute commands:
gnome-terminal [-e, --command=STRING] [-x, --execute]
You probably need to add -x option:
x, --execute
Execute the remainder of the command line inside the terminal.
so:
os.system("gnome-terminal -x python f.py")
That would not run your process in the background unless you add & to your command line BTW.
The communicate attempt would need a newline for your input but should work too, but complex processes like terminals don't "like" being redirected. It seems like using an interactive tool backwards.
And again, that would block until termination. What could work would be to use p.stdin.write("python f.py\n") to give control to the python script. But in that case it's unlikely to work.
So it seems that you don't even need python do to what you want. You just need to run
python f.py &
in a shell.
As of GNOME Terminal 3.24.2 Using VTE version 0.48.4 +GNUTLS -PCRE2
Option “-x” is deprecated and might be removed in a later version of gnome-terminal.
Use “-- ” to terminate the options and put the command line to execute after it.
Thus the preferred syntax appears to be
gnome-terminal -- echo hello
rather than
gnome-terminal -x echo hello
Here is a complete example of how you would call a executable python file with subprocess.call Using argparse to properly parse the input.
the target process will print your given input.
Your python file to be called:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--file", help="Just A test", dest='myfile')
args = parser.parse_args()
print args.myfile
Your calling python file:
from subprocess import call
#call(["python","/users/dev/python/sandboxArgParse.py", "--file", "abcd.txt"])
call(["gnome-terminal", "-e", "python /users/dev/python/sandboxArgParse.py --file abcd.txt"])
Just for information:
You probably don't need python calling another python script to run a terminal window with a process, but could do as follows:
gnome-terminal -e "python /yourfile.py -f yourTestfile.txt"
The following code will open a new terminal and execute the process:
process = subprocess.Popen(
"sudo gnome-terminal -x python f.py",
stdout=subprocess.PIPE,
stderr=None,
shell=True
)
I am running a uWS server with this.In my case Popen didn't help(Even though it run the executable, still it couldn't communicate with a client -: socket connection is broken).This is working.Also now they recommends to use "--" instead of "-e".
subprocess.call(['gnome-terminal', "--", "python3", "server_deployment.py"])
#server_deployment.py
def run():
execution_cmd = "./my_executable arg1 arg2 dll_1 dll_2"
os.system(execution_cmd)
run()

how to execute remote python to open a web on remote machine by using a command on a local machine

I've been searching on net for a long time but I still don't get the answer.
Let me give an examle to describe my question more clearly:
machine A(local) is now conneted with machine B(remote).ALL I WANT TO DO is to :
run a command on A(local),then stop and wait ,and do nothing,and then,a web page is opened on B(remote) automatically.
P.S this python program is stored on machine B.
Here's what I've achived by now:
This is my python program named test.py,and it is stored on B under /home/pi/Documents:
import webbrowser
webbrowser.open('http://www.google.com')
On A,I used command:
ssh <username of B>#<ip of B> python /home/pi/Documents/test.py
After running the above command on A,there is no errors on A but also no action on B.
if I change the command into creating a file on B or sudo reboot,then after running this command there will be a file on B created or B is shut down successfully.
if I change the python program into printing something,like:
print("hello from B")
the content is magically printed on A's terminal.
It seems this command does not work well if I want to open a web on B or print somthing on B.
Can anyone help me with this or is there any other way to accomplish it?
helpless..
Someone has any ideas please???
Thanks in advance!
Assuming B is a Linux or Unix-like system, you have a DISPLAY problem. The webbrowser module locates a browser on the machine, and tries to open it on current display. It works when you launch it localy, but a ssh session has by default no configured display, so any attempt to launch a XWindow (GUI) application will fail.
The rationale behind it is that the -X and -Y flags of the ssh command allow to pass the client display to the server and open the window on the local screen (in your example on A). So if the permissions of the X servers on A and B are compatible, you could try:
A$ ssh -Y <username of B>#<ip of B> # open an interactive shell on B
B$ echo $DISPLAY # control the DISPLAY env variable
-> localhost:10.0 # common value for ssh transported DISPLAY
B$ python /home/pi/Documents/test.py # open the window on A
To force the opening on B, you could set the DISPLAY to localhost:0.0 (primary XWindow)
A$ ssh ssh <username of B>#<ip of B> # open an interactive shell on B
B$ DISPLAY = localhost:0.0 # sets the DISPLAY env variable
B$ export DISPLAY
B$ python /home/pi/Documents/test.py # open the window on B
You might need to tweek authorization of the XWindow servers (or use the awful xhost +) on A and/or B to make the above examples work
Once you have been able to successfully open a window on the proper screen, you will just have to set the DISPLAY environment variable to the correct value in your Python script before opening the browser window.
One of the simplest solutions is to use redirect of stdin
$ ssh pi#B python <<EOF
> print "Hello World from B"
> EOF
Hello World from B
$
However, if the script is quite big, it is better to copy py file to server B and then call ssh with the file name as #Eliethesaiyan suggested.
$ scp X.py pi#B:/home/pi/
X.py 100% 26 0.0KB/s 00:00
$ ssh pi#B python X.py
Hello World from B
$
I've tested this using a VM running Ubuntu, which OS are you running on your remote system? Here's my launch_google.py:
import os
os.environ["DISPLAY"] = ":0"
import webbrowser
webbrowser.open("https://google.com")
Launch this using:
ssh <user>#<IP Address> "python launch_google.py&"
I included the ampersand otherwise the ssh session remains open. The python process doesn't need to keep running.
It is important to set the DISPLAY environment variable before importing the webbrowser module, otherwise the browsers won't be setup correctly. You can verify this running python via SSH:
>>> import os
>>> "DISPLAY" in os.environ
False
>>> import webbrowser
>>> len(webbrowser._browsers)
0
>>> webbrowser.open("https://google.com")
False
>>> os.environ["DISPLAY"] = ":0"
>>> reload(webbrowser)
<module 'webbrowser' from '/usr/lib/python2.7/webbrowser.pyc'>
>>> len(webbrowser._browsers)
3
>>> webbrowser.open("https://google.com")
True
>>>

xterm -e - do not close xterm after command

I had wrote scirpt in python which execute bash command using system.os("cmd"). I wouldn't like to have output of bash script on same terminal what I have python script output, so I execute bash command via xterm -e. My code is similar to this:
# python
import os
os.system("xterm -e 'ls'")
This code works but after ls end the new terminal disappear. I want to have stay this terminal.
You can let the the window stay until the user presses a key with read:
os.system("xterm -e 'ls; read'")
or you just run a new terminal of xterm which runs until it is closed:
os.system("xterm")
Note 1: The os.system function seems to block the python script until the external process (xterm in this case) has finished. So you can use it in a loop where each bash window has to be closed before a new one is opened.
Note 2: the python documentation suggests to use subprocess.call
The following should work. I tried it on a Mint linux box.
import os
os.system("xterm -hold -e 'ls' &")
It's almoust good, but:
import os
os.system("xterm -hold -e 'my_cmd_1' &")
os.system("xterm -hold -e 'my_cmd_2' &")
my_cmd_2 can not start before my_cmd_end_1

Categories

Resources