简体   繁体   中英

Open python program within a different command-line-interface(CLI)?

I need a python script that opens another CLI and run it in there. Eg

python C:\Python27\Scripts\script.py test
python /path/to/script_folder/script.py test

I need to support both Unix and Windows.

Any suggestions?

If you are you looking for running an interactive console in your script, then I'd use something like this:

import code
console = code.InteractiveConsole()
console.interact()

You can find more information in the code module documentation . In particular, you might be interested in the runcode and runsource methods.

If you are looking for running a script and continue after the script execution in a python shell, then I'd use something like this:

$ python -i <path_to_script>

After much deliberation, reading this question and others, I found the solution, had my "man am I dumb" moment, and in the end, this will do the trick:

command = r'start cmd.exe python "' + <script> + r'" [args]'
os.system(command)

The keyword there is "start." It does magic that basically tells Windows that the file to execute has no relation to the actual caller, and viola, you have a new console.

I'm not sure about Unix, but I assume it'd be similar, using gnome-terminal somehow.

If I understand your question correctly, you want to:

  1. launch a python script
  2. This script should itself launch a new terminal window
  3. In this new terminal, another python script should be run

Depending on whether point 3 must then leave the terminal window open, solutions can be very different.

If you don't need the window open, just go for os.system or subprocess . If you are only running a python script, you might get away with just specifying "python" as the executable, hence being cross-platform.

If you do need the window open, you'll have to launch the specific shell+terminal, which is OS-specific (cmd.exe in Windows; in the unix world, /bin/sh, /bin/bash or whatever else, probably wrapped by xterm ).

But to be honest, unless there's some very specific requirement to have a completely different terminal session open, what you should do is just import the second module and run it from the first, or read it in memory and then use exec .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM