-1

My python script generate a proper command that user need to run in the same console. My scenario is that user is running a script and then as a result see the command that must to run. Is there any way to exit python script and send that command to console, so user do not need to copy/paste?

9769953
  • 4,966
  • 3
  • 14
  • 24
route00
  • 15
  • 2
  • 1
    Why not just use `subprocess` to execute the command without the user having to press Enter? – BoarGules Mar 25 '19 at 08:39
  • Python 2 or Python 3? What version are you using? What minor version, more specifically? – 9769953 May 02 '19 at 12:09
  • The answer may depend on the operation system and/or command line you are using. In Linux, you could just pipe the output of the script to a shell interpreter: `python script.py | sh` – tobias_k May 02 '19 at 12:12

2 Answers2

0

A solution would be to have your python script (let's call it script.py) just print the command: print('ls -l') and use it in a terminal like so: $(python3 script.py). This makes bash run the output of your script as a command, and would basically run a ls -l in the terminal.

You can even go a step beyond and create an alias in ~/.bashrc so that you no longer need to call the whole line. You can write at the end of the file something like alias printls=$(python3 /path/to/script.py). After starting a new terminal, you can type printls and the script will run.

A drawback of this method is that you have no proper way of handling exceptions or errors in your code, since everything it prints will be run as a command. One way (though ugly) would be to print('echo "An error occured!"') so that the user who runs the command can see that something malfunctioned.

However, I'd suggest going for the "traditional" way and running the command directly from python. Here's a link to how you can achieve this: Calling an external command in Python.

Bogsan
  • 531
  • 4
  • 10
0

Python can run system commands in new subshells. The proper way of doing this is via the subprocess module, but for simple tasks it's easier to just use os.system. Example Python script (assuming a Unix-like system):

import os
os.system('ls')
jmd_dk
  • 8,399
  • 4
  • 48
  • 72