Start a process in a different console window - python

How can I start a process to run in a different console window using Python in Linux, something similar to this in windows(using start):
import os
os.system('start dir c:\*.* /s')

xterm -e should do the trick for you.
-e program [ arguments ... ]
This option specifies the program (and its command line arguments) to be
run in the xterm window. It also sets
the window title and icon name to be
the basename of the program being
executed if neither -T nor -n are
given on the command line. This must
be the last option on the command
line.
E.g.
import os
os.system("xterm -e 'your command'")

Related

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()

Send commands to the opened python terminal

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
>>>

how to give multiple command to cmd.exe after opening it using python [duplicate]

I'm trying to open a new command window in a BAT file:
start %windir%\system32\cmd.exe
After it opens, I'd like to execute a BAT command in the new window:
echo "test in new window"
How can I do this?
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command
specified by string and then
terminates
/k Carries out the
command specified by string but
remains
Consult the cmd.exe documentation using cmd /? for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Examples:
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a long filename:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
The above answers helped me. But still required some figuring out. Here is an example script I use to start 3 processes for web development. It results in 3 windows staying open, as they need to run continously.
Mongo is globally added to my path, so I don't need to cd like I do for the other two programs. Of course the path to your files will vary, but hopefully this will help.
:: Start MongoDB
start cmd.exe /k "mongod"
:: cd app directory, and start it
cd my-app
start cmd.exe /k "npm run dev"
:: cd to api server, and start that
cd ../my-app-api
start cmd.exe /k "npm run dev"
This is not very easy.
The best approach is to have the part of your script that you want to be executed in a "new window" to be in a separate .bat file. This might be impractical if e.g. you need a lot of state from the rest of your script (variables, etc). One option is to pass any values you need (e.g. dir to operate in) to the batch file:
start cmd.exe stuff.bat %this_dir%
If you have a large amount of state to transmit you might consider generating a batch file at runtime:
set foo=Hello, World
set list_me=%userprofile%
set tmpdir=c:\windows\temp
set tmp=%tmpdir%\tmp.foo
del /q /f "%tmp%"
echo.echo %foo%>>"%tmp%"
echo.dir "%list_me%">>>"%tmp"
start cmd.exe "%tmp%"
del /q /f "%tmp%"
Obviously this is a trivial example.
Thanks to all here in Stack Overflow; this solution solves the above question but is extended to automatically run these tasks:
I want to run my rails server
Run a rake jobs:worker for my delayed_job gem too
and Open default internet browser to show my page
finally, to leave a cmd window open for any extra commands during my session.
I guess my project is called "antiquorum."
Create an "init.bat" file in your %USERPROFILE% directory (open a cmd window and take a look at the path to the left of the cursor to know what %USERPROFILE% is)
#echo off
cd C:/projects/rails3/antiquorum
if "%1" == "antiquorum" GOTO start
if "%1" == "worker" GOTO worker
if "%1" == "server" GOTO server
if "%1" == "" GOTO end
:start
start cmd /k %USERPROFILE%\init.bat worker
start cmd /k %USERPROFILE%\init.bat server
TIMEOUT 30
start "" "http://localhost:3000/"
GOTO end
:server
rails s
GOTO end
:worker
rake jobs:work
:end
In a new command line window type: C:> init antiquorum
The code opens two more cmd windows and a browser. TIMEOUT avoids errors in the browser.
The :start section does the work.
You can run tasks 1,2 or 4 separately by typing params as: server, worker, or none to leave a cmd opened in root of "antiquorum" project.
Enjoy.
Adding /k between two commands executes both command in order.
Example:
cmd /k echo "hello"
this command will first open command prompt then execute echo "hello" command
If I understand you correctly doing this in side your bat file will open Command prompt and print your message to screen.
cmd.exe hello world
hope this helps.
to run a python file in a new cmd window with spaces in the file name:
start cmd.exe /k python "C:\Program Files\HelloWorld.py"
Extending answer from #Dan Zuzevich. Below is CD "Change Directory" if your target file is on different drive. For example it have to call file from drive C and drive D.
:: Start MongoDB
start cmd.exe /k "mongod"
:: cd app directory, and start it
cd C:\project\dev
C:
start cmd.exe /k "npm run dev"
:: cd to api server, and start that
cd D:\api\server
D:
start cmd.exe /k "npm run dev"
I wanted my window to remain open after I killed or restarted Firebase so I used two batch files.
Desktop file for easy access: run_firebase.bat:
--------------START FILE CONTENTS--------------
start cmd /k C:\dev\init_firebase_batch.bat
---------------END FILE CONTENTS---------------
Batch file to run the intended results: C:\dev\init_firebase_batch.bat
--------------START FILE CONTENTS--------------
cd C:\dev\aptr_datasync\aperture-customer-hub
firebase emulators:start
---------------END FILE CONTENTS---------------
So ... double click run_firebase.bat and it runs the second batch. After Ctrl+C out of my process the window remains open. Seems trivial but I don't like distractions while I'm working on code.
I only spent time solving because I thought it would be simple. Hopefully this creates that simplicity for others.
I think this checks off the questions in the initial post:
[x] I'm trying to open a new command window in a BAT file
[x] After it opens, I'd like to execute a BAT command in the new window
I needed to run an environment and then use python while in that environment.
If my folder structure is:
C:\environments>
C:\environments\encrypted_stuff>
C:\environments\encrypted_stuff\p1>
C:\environments\encrypted_stuff\p2>
And I wanted to activate the "encrypted_stuff" environment then call a script from p2, I might type this in a bat that is stored in C:\environments\p2.bat
start cmd /k "Scripts\activate && cd p2 && python p2_script.py"
Then I can have a bat file for any of the scripts and all would use my "encrypted_stuff" environment. Now I can click the bat file from the desktop and it will load my specific environment and then run the script in that environment.

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