Can a batch file execute commands within a python shell? - python

Can I use a batch file to start a python shell and execute commands? I know that
python
will start a python shell, but a batch file containing
python
1+1
will first run python, and then only when you quit python will it attempt to run 1+1. It will not execute any commands within the python shell.

After a little searching around, I managed to find this website that has a method to do this. As you will see on the website, all you need to do is:
#setlocal enabledelayedexpansion && python -x "%~f0" %* & exit /b !ERRORLEVEL!
#start python code here
print "hello world"
This didn't work for me, however I thought it might help.
I haven't been able to find any other source that says it's possible.
Just thought of something else that I haven't tested. I combined Bear's answer and mine.
#for /f "skip=1 delims=" %i in (%0) do #python -c "%i"
#Start Python here.
However, the other method should be used.

I know this has an accepted answer but you might also try the -c argument for the python command. python -c "print(1+1)" will print "2" to the console. The -c flag means "command" and is interpreted by python immediately.

Related

Calling PowerShell from Python using Notepad++

I thought it might be time to start using PowerShell instead of cmd. I currently run Python scripts from Notepad++ with the following commnad:
cmd /c cd "$(CURRENT_DIRECTORY)" &python -i "$(FILE_NAME)"
How should I modify this to get the same behaviour in PowerShell please?
I tried
powershell -noexit cd "$(CURRENT_DIRECTORY)" &python -i "$(FILE_NAME)"
but I got an error about ampersands. I know very little about PowerShell or cmd in general - I just use them to run my Python scripts.
After a bit more digging I found a solution:
powershell -noexit cd '$(CURRENT_DIRECTORY)'; python -i '$(FILE_NAME)'
PowerShell seems to prefer single quotes for paths so I wrapped $(CURRENT_DIRECTORY) and $(FILE_NAME) in single quotes.
Also, & is replaced by ; for multiple commands.
If there is a more "correct" way of doing this, please let me know.

Execute python code from within a shell script

I want to have some python code run within a shell script. I don't want to rely on an external file to be ran. Is there any way to do that?
I did a ton of googling, but there aren't any clear answers. This code is what I find... But it relies on the external python script to be ran. I want it all within one file.
python python_script.py
You can use a so-called "here document":
#!/usr/bin/env bash
echo "hello from bash"
python3 - <<'EOF'
print("hello from Python 3")
EOF
The single quotes around the first EOF prevent the usual expansions and command substitions in a shell script.
If you want those to happen, simply remove them.
If you mean within a BASH shell script without executing any external dependencies, I am afraid you're out of luck, since BASH only interprets its own scripting language.
Your question is somewhat like asking "Can I run a Java .class file without the JVM"? Obviously, you will always have the external dependency of the JRE/JVM. This is the same case, you depend on the external Python compiler and interpreter.
Optionally, you have the option of including the python script inline, but it would still require the python executable.
This works:
python -c 'print("Hi")'
Or this with BASH redirection:
python <<< 'print("Hi")'

How to create tcsh aliases using python?

I am trying to created aliases for tcsh from a python script (running Python 2.7.1).
Once the aliases are created I want to use them in the same shell I ran the python script in.
I tried:
os.system('alias test "echo test"')
but I get the following error:
sh: line 0: alias: test: not found
sh: line 0: alias: echo test: not found
I then tried:
os.system(r"""/bin/csh -i -c 'alias test "echo test"'""")
And then no errors occurred, but the alias did not register, and therefore I could not use it.
The result I'm looking for is this:
tcsh>python my_script.py
tcsh>test
test
Thanks!
os.system executes that command in a subshell (the bourne shell by the look of it), so even if your syntax was correct alias test="echo test", it would not persist after the call (since the subshell closed).
But this seems like an XY question. You ask about Y - the solution you had in mind, and not about X - your problem.
If you simply want to create a bunch of aliases at once, why not use a c-shell script!? (Why you are torturing yourself with c-shell is another matter entirely).
Your python script cannot execute anything in the context of your shell. While you could use subprocess.call(..., shell=True) this would use a new shell and thus not update your existing shell.
The only way to do what you want is to make your python script write valid shell commands to stdout and then, instead of just executing it, you need to make your shell evaluate the output of your python script.

os.system doesn't work in Python

I'm working on windows vista, but I'm running python from DOS command. I have this simple python program. (It's actually one py file named test.py)
import os
os.system('cd ..')
When I execute "python test.py" from a Dos command, it doesn't work.
For example, if the prompt Dos Command before execution was this:
C:\Directory>
After execution, must be this:
C:\>
Help Plz.
First, you generally don't want to use os.system - take a look at the subprocess module instead. But, that won't solve your immediate problem (just some you might have down the track) - the actual reason cd won't work is because it changes the working directory of the subprocess, and doesn't affect the process Python is running in - to do that, use os.chdir.
I don't really use Windows, but you can try cmd /k yourcommandhere. This executes the command and then returns to the CMD prompt.
So for example, maybe you can do what you want like this:
subprocess.call(['cmd', '/k', 'cd .. && prompt changed'])
As I said, I am not familiar with Windows, so the syntax could be wrong, but you should get the idea.
In case you don't know, this is a different CMD instance than the one you were in before you started your python script. So when you exit, your python script should continue execution, and after it's done, you'll be back to your original CMD.

How to start a Python ipython shell, automatically run inside it a few commands, and leave it open?

I tried
echo "print 'hello'" | ipython
Which runs the command but ipython immediately exits afterwards.
Any ideas? Thanks!
Edit:
I actually need to pass the command into the interactive Django shell, e.g.:
echo "print 'hello'" | python manage.py shell
so the -i switch gimel suggested doesn't seem to work (the shell still exits after execution)
Use the same flag used by the standard interpreter, -i.
-i
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.
A Linux example, using the -c command line flag:
$ ipython -i -c 'print "hello, ipython!"'
hello, ipython!
In [2]: print "right here"
right here
In [3]:
Try using the ipy_user_conf.py inside your ~/.ipython
I'm not sure of ipython but the basic python interpreter has a command line parameter to give you the prompt after it executes the file you've given it. I don't have an interpreter handy to tell you what it is but you can get it using python --help. It should do exactly what you want.
Running a custom startup script/profile script with the Django shell was marked as closed: wontfix.
However, there is a shell_plus Django extension discussed in that ticket which seems to do what you want. I haven't had a chance to check it out, but it looks like at the very least it can run a load to auto import all the models of all installed apps (which I usu. find myself doing).
Shell plus.py in django-command-extensions on Google Code
django-command-extensions homepage on Google Code
django_extensions on Github

Categories