I have a batch program that simply pings in loop with 'ping adress -t'. Adress being whatever I'm trying to ping at the time.
I'd like to do something similiar with python, but without the popup of a command prompt window and thus I'd like to avoid anything that would do this. I want a way to print it ONLY to the python window, so I can use it in my Tkinter program.
This is what I would originially thought would work, and it does, but I want the output to be in the python window, not in the command prompt.
import subprocess
subprocess.call(["ping", "google.com", "-t"])
What about:
import subprocess
subprocess.call(["ping", "-t"])
Related
How do I make a program where I can run a piece of code, then show the results? So if I make my program run python --version it should print something like Python 3.8.3 (depends on what version you are on), but you get the point
PS: I know this has been posted before, but they don't work for me :(
Thanks!!
So here I made a very simple version of what You may want (type in python --version to try out):
from tkinter import Tk, Text
import subprocess
def run(event):
command = cmd.get('1.0', 'end').split('\n')[-2]
if command == 'exit':
exit()
cmd.insert('end', f'\n{subprocess.getoutput(command)}')
root = Tk()
cmd = Text(root)
cmd.pack()
cmd.bind('<Return>', run)
root.mainloop()
the subprocess.getoutput() gets the output the cmd would give if the given command was used
EDIT (moved comment here):
there are some limitations however for example running pause will just crash tkinter and the output will be given only after command has finished running for example if You tracert google.com it may take a while and during that the window will be unresponsive until it completes the process and then puts it all out (maybe for that it is possible to use threads to not make the window unresponsive at least)
EDIT (28.07.2021.):
Probably better to use subprocess.Popen and stream data from there
Actually, I have written a code where I've to lunch the application such that I've to click the on-screen keyboard using this pyautogui.click(). But it is not working on on-screen keyboard. I'll be pleased to have your precious opinion. Thanks in advance.
import os
import pyautogui as pg
import time
x= 195
y=505
secret="secretpassword"
command = "application"
os.system(command)
pg.click(x, y)
pg.typewrite(secret)
pg.typewrite(["enter"])
If the application is already lunched this is working but i want to lunch it with os.system(command)
and after that enter my password and access to the application.
Am I doing something wrong ?
I changed
os.system(command)
with
subprocess.Popen(command)
Now it's working
subprocess.Popen() is strict super-set of os.system().
os.system() will block and wait for the application to exit.
This means that your click, in fact, will not execute until the opened appication closes.
To verify this, you can open a (python) shell and run following code:
import os
import pyautogui
def test():
os.system('<something simple opening a window>')
pyautogui.typewrite("I'm in the shell again!")
test()
To run your script as you want, use os.popen, or, even better, subprocess.Popen. These will run the command without blocking.
If you do this, keep in mind your application will have startup time, so you will want to wait some time after the call as noted in the comments under your question.
I use Application from pywinauto.application
After logging in i want it to execute commads like :
putty.type_keys("ls")
putty.type_keys("{ENTER}")
To execute next command i need to wait for this one to end. Instead of typing something like :
time.sleep(5)
I need the program to know when the command is done and ready for next command, not to wait X seconds and hope the running task will be over untill that(for example downloadign a file). I looked up into "wait()", but didn't find anything useful. Any help?
You don’t need pywinauto for executing console commands by ssh! Just do something like this:
import subprocess
output = subprocess.check_output(“ssh user:password#hostname ls -l /home”)
for line in output.split(“\n”):
subpath = “ “.join(line.split(“ “)[1:])
print(subpath)
I am running several processes over a cluster.
I start every process separately using screen command.
It allows me to disconnect from the cluster and when connected view my processes.
Starting all the screens one by one is a painful job.
I am wondering if we could do it with a python script.
The scrip opens the new shell creates the screen runs the process and disconnects.
Writes info about all the started processes in a text file like process id starting commands etc.
Secondly, I would like to stop the processes, I would like to put the pid to file and just run a command which will kill all the mentioned processes.
for example
the smaple inut file looks like
process_name command
123 python batch_training.py
I would like to start the screen with the name given in process_name and the commend will be executed in the corresponding frame.
Thanks
Can you give the screen object a command in python?
Like:
from os import system
command = 'screen ' + '/dev/ttyUSB0 38400'
result = system(command)
result('ATZ')???
If you want to run your command without opening screen session, you should also use -dmS options with screen. So if you want to do that with python, Your code could look like this:
import subprocess
subprocess.call(["screen", "-dmS", "screen_name_1", "top"])
subprocess.call(["screen", "-dmS", "screen_name_2", "top"])
subprocess.call(["screen", "-r"])
Try to use "os.system()" with standart Linux commands.
e.g.:
os.system("screen nano")
In general, in python, you can run system commands by running
from os import system
and then
system('whatever_shell_command')
So in your case you would type:
from os import system
system('screen')
Unfortunately (this is only sort of related) you can't run more then one command together, so
system('shell_command ', argument)
will not work.
so if you want to do that, you will need to concatenate the two strings:
full_command = 'shell_command ' + argument
system(full_command)`
I have a small script that launches and, every half hour, feeds a command to a java program (game server manager) as if the user was typing it. However, after reading documentation and experimenting, I can't figure out how I can get two things:
1) A version which allows the user to type commands into the terminal windoe and they will be sent to the server manager input just as the "save-all" command is.
2) A version which remains running, but sends any new input to the system itself, removing the need for a second terminal window. This one is actually half-happening right now as when something is typed, there is no visual feedback, but once the program is ended, it's clear the terminal has received the input. For example, a list of directory contents will be there if "dir" was typed while the program was running. This one is more for understanding than practicality.
Thanks for the help. Here's the script:
from time import sleep
import sys,os
import subprocess
# Launches the server with specified parameters, waits however
# long is specified in saveInterval, then saves the map.
# Edit the value after "saveInterval =" to desired number of minutes.
# Default is 30
saveInterval = 30
# Start the server. Substitute the launch command with whatever you please.
p = subprocess.Popen('java -Xmx1024M -Xms1024M -jar minecraft_server.jar',
shell=False,
stdin=subprocess.PIPE);
while(True):
sleep(saveInterval*60)
# Comment out these two lines if you want the save to happen silently.
p.stdin.write("say Backing up map...\n")
p.stdin.flush()
# Stop all other saves to prevent corruption.
p.stdin.write("save-off\n")
p.stdin.flush()
sleep(1)
# Perform save
p.stdin.write("save-all\n")
p.stdin.flush()
sleep(10)
# Allow other saves again.
p.stdin.write("save-on\n")
p.stdin.flush()
Replace your sleep() with a call to select((sys.stdin, ), (), (), saveInterval*60) -- that will have the same timeout but listens on stdin for user commands. When select says you have input, read a line from sys.stdin and feed it to your process. When select indicates a timeout, perform the "save" command that you're doing now.
It won't completely solve your problem, but you might find python's cmd module useful. It's a way of easily implementing an extensible command line loop (often called a REPL).
You can run the program using screen, then you can send the input to the specific screen session instead of to the program directly (if you are in Windows just install cygwin).