How do we create alias from python program/script? [duplicate] - python

This question already has an answer here:
create unix alias using a python3 script
(1 answer)
Closed 2 years ago.
I want to create an alias' through python program. I intend to use python as a replacement for shell scripting.
What I tried is:
import os
os.system('alias go2dir="cd /i/want/to/goto/this/dir"')
...and it does not work. I know the reason - that system command 'alias...' is getting executed in another shell and not in the current one where this python script is executed. So, that alias is not available to this shell.
What I don't know is - (In general,) how do we execute a command from a python program in the same shell where this python program is being executed. So that (in this case) the alias is available till the shell terminal is open?

The way other applications that want to automate actions in the user's shell work is that they write shell commands to their standard output. Then you can execute them with eval.
makealias.py:
print('alias go2dir="cd /i/want/to/goto/this/dir"')
Then in bash:
eval "$(python makealias.py)"
An example of a standard Unix program that works like this is tset with the -s option.

Related

Opening Python code with a specific version [duplicate]

This question already has answers here:
Multiple Python versions on the same machine?
(11 answers)
Closed 3 years ago.
while there are multiple versions of Python installed on a Linux machine, is there a way to mention in the script to be open with a specific version, say, 3.8 even if we issue the #python script.py as opposed to python3.8 script.py ?
I don't want to use Linux alias command. I wanna know if that is possible to be accomplished within the script
Use shebang. #!/usr/bin/python
In the first line of the code with the serial number of Python you want at the end.
You'll need to then run your script like ./my_script.py
You can select the interpreter by adding
#!/usr/bin/env pythonXX
as the first line in your script, provided the version is in the path.
You can also invoke the interpreter directly with the script as the argument.
pythonXX script.py
Depending on your situation
pythonXX -E script.py
might be better. That way the interpreter ignores paths set by environmental variables.
For more details view
https://docs.python.org/3/using/cmdline.html

Run Python script on Terminal and keep using the terminal afterwards [duplicate]

This question already has answers here:
Run a shell script and immediately background it, however keep the ability to inspect its output
(3 answers)
Closed 4 years ago.
I have a script that I activate via the terminal that listens to events. I want to keep using the terminal after the script runs, but the script is running and I can't type anything. The only way I know that lets me keep typing is by using the Ctrl + C combination, but this stops the script.
So how can I run the script in the background and keep using the terminal without terminating it?
Edit: I tried to use the '&' operator but it didn't work:
You can run your script in the background with:
python myscript.py &
If your script does output something you can suppress the output with:
python myscript.py 1>/dev/null 2>&1 &
Or save the output for later:
python myscript.py 1>myoutputfile 2>&1 &
# ...
less myoutputfile
Another alternative would be to use for example screen or tmux.

Piping variables from shell script to Python [duplicate]

This question already has answers here:
Assign environment variables from bash script to current session from Python
(3 answers)
Closed 5 years ago.
I have a script called "script.sh," whose contents are:
#!/bin/sh
export A=5
I want to execute this script from within python (iPython actually) and read the variable 'A'.
import os
import subprocess
subprocess.call('./script.sh')
A=os.environ['A']
Unfortunately, this doesn't seem to work, giving me an error that A cannot be found. If I understand correctly, subprocess is actually running in a different shell than the one that os.environ queries. But then why can't I run something like:
subprocess.call('echo $A')
?
What should I change to make this work? In general, I just want to obtain the value of "A" from the script, preferably by executing the script through some form of shell (the actual script is quite long).
For some more info, the script will contain login credentials, so ideally I'd like a safe,minimalist way of accessing their values.
You need to source the script in the subshell (so it sets the variable in the same shell process), then echo the variable in that subshell:
a = subprocess.check_output('source ./script.sh; echo "$A"', shell=True)
Then you can read from the pipe to get the value of the variable.
The trick will be to spawn a new shell and tell it to both interpret your script's code, and can print out its environment in a way that Python can read it. A one-liner:
In [10]: subprocess.check_output(["bash", "-c", "source ./script.sh; env"])
Out[10]: '...\nA=5\n...'
What's happening: In general, environment variables are set at the beginning of a program, and any subprocesses can't modify their parent's environment; it's a sort of sandbox. But source is a bash builtin where bash says "instead of spawning script.sh as a new (sub-)subprocess which couldn't modify my environ, run the lines of code as myself (bash) and modify my environ accordingly for future commands". And env is tacked on so that bash prints the environment separated by newlines. check_output simply grabs that output and brings it back into Python.
(As a side note, that source command is what you use to update a shell to use a certain virtualenv: source my_project/bin/activate. Then the $PATH and other variables of your current shell are updated to use the virtualenv python and libraries for the rest of that session. You can't just say my_project/bin/activate since it would set them in a subshell, doing nothing :))

Python - Code does not run without #!/usr/bin/python [duplicate]

This question already has answers here:
Why do people write #!/usr/bin/env python on the first line of a Python script?
(22 answers)
Closed 7 years ago.
Okay I am new to Python, but my code does not run if the line
#!/usr/bin/python
is not present at the beginning of the file. Why is that ? What does it mean ? I thought it was used for to denote a python version if there were multiple versions installed.
#!/usr/bin/python
def main():
a = [1,2,3]
print a
if __name__ == "__main__":
main()
Omitting the #!/usr/bin/python gives the following error only if I execute it using
./test.py on Ubuntu
if however I use the python command to run then it runs fine without the /usr/bin line.
The first line of the script beginning with #! is a shebang (sometimes called a hash-bang).
The following executable path denotes which interpreter should be used to process the following code (in your case, /usr/bin/python).
If you run the script from the shell with python test.py, you don't need a shebang - the executable is python and the script is passed to it as an argument.
In Unix you can tell a file how it should be opened if it contains a script language (in your case Python).
This line is known as Shebang.
./filename is used to run executable files, to execute it you need to specify the application required.
Whereas, in using python filename.py you already specify the application to use that is python in this case.

Running shell commands within python interpreter [duplicate]

This question already has answers here:
How do I execute a program or call a system command?
(65 answers)
Closed 8 years ago.
Is there a simple method for calling shell command line arguments (like ls or pwd) from within python interpreter?
In plain python, you need to use something along the lines of this:
from subprocess import check_output
check_output("ls", shell=True)
In IPython, you can run either of those commands or a general shell command by starting off with !. For example
! echo "Hello, world!" > /tmp/Hello.txt
If you're using python interactively, you would almost certainly be happier with IPython.
If you meant to use the Python shell interactively while being able to call commands (ls, pwd, ...) check out iPython.

Categories

Resources