I am trying out the sys library in python. In command prompt I am using this.
>>>import sys
>>>sys.ps1 ='$'
#my own input 'print 'test print''
$print 'test print'
test print
That worked in CLI, however, when I tried to do it in a python file and run it in CLI ( python file.py did not return anything.
#!/usr/bin/python
import sys
sys.ps1= '$'
Am I missing anything in the file?
What are you trying to do? sys.ps1 will just set the prompt for the python interpreter, so as soon as it exits it's effect is gone again. When running a file, there is no command-line.
If you want to see this have an effect, try running this with python -i file.py - this will run the command, and then drop you into the interactive shell, which should have PS1 set to $ now
Related
I have a Python script that I want to be able to debug from the command line. Let's say it's called simple.py, and it contains the following code:
var1 = "Hello"
var2 = "World"
print(var1, var2)
I want to debug this. Of course I can use the debugger from the command line:
python -m pdb simple.py
But I want to debug this specifically from within another python file. I've tried using subprocess to do this, by putting this code into another script, debug.py:
import subprocess
subprocess.Popen(["bash", "-ic", "python -m pdb simple.py"])
When I run it in a Bash shell, this happens:
$ python debug.py
$ > /[path]/simple.py(1)<module>()
-> var1 = "Hello"
(Pdb) n
bash: n: command not found
$
So I've typed "n", expecting the debugger to move to the next line. Instead, it seems to just go straight back to Bash, and the debugger doesn't do anything.
Any idea why this happens? Is there a way to spawn a Bash shell containing a Python debugger from within a Python script, which I can actually use to debug?
Your debug.py finish its run and you are back to the shell (try typing ls instead, and see what happens)
What you are looking for is a way to interact with the other process, you need to get the input from your stdin and pass it to the other process stdin. It can looks something like:
import subprocess
p = subprocess.Popen(["python3", "-m", "pdb", "test.py"])
while True:
cmd = input()
p.stdin.write(cmd.encode())
Not sure if this is possible. I have a set of python scripts and have modified the linux PATH in ~/.bashrc so that whenever I open a terminal, the python scripts are available to run as a command.
export PATH=$PATH:/home/user/pythonlib/
my_command.py resides in the above path.
I can run my_command.py (args) from anywhere in terminal and it will run the python scripts.
I'd like to control this functionality from a different python script as this will be the quickest solution to automating my processing routines. So I need it to open a terminal and run my_command.py (args) from within the python script I'm working on.
I have tried subprocess:
import subprocess
test = subprocess.Popen(["my_command.py"], stdout=subprocess.PIPE)
output = test.communicate()[0]
While my_command.py is typically available in any terminal I launch, here I have no access to it, returns file not found.
I can start a new terminal using os then type in my_command.py, and it works
os.system("x-terminal-emulator -e /bin/bash")
So, is there a way to get the second method to accept a script you want to run from python with args?
Ubuntu 16
Thanks :)
Popen does not load the system PATH for the session you create in a python script. You have to modify the PATH in the session to include the directory to your project like so:
someterminalcommand = "my_command.py (args)"
my_env = os.environ.copy()
my_env["PATH"] = "/home/usr/mypythonlib/:" + my_env["PATH"]
combine = subprocess.Popen(shlex.split(someterminalcommand), env=my_env)
combine.wait()
This allows me to run my "my_command.py" file from a different python session just like I had a terminal window open.
If you're using Gnome, the gnome-terminal command is rather useful in this situation.
As an example of very basic usage, the following code will spawn a terminal, and run a Python REPL in it:
import subprocess
subprocess.Popen(["gnome-terminal", "-e", "python"])
Now, if you want to run a specific script, you will need to concatenate its path with python, for the last element of that list it the line that will be executed in the new terminal.
For instance:
subprocess.Popen(["gnome-terminal", "-e", "python my_script.py"])
If your script is executable, you can omit python:
subprocess.Popen(["gnome-terminal", "-e", "my_script.py"])
If you want to pass parameters to your script, simply add them to the python command:
subprocess.Popen(["gnome-terminal", "-e", "python my_script.py var1 var2"])
Note that if you want to run your script with a particular version of Python, you should specify it, by explicitly calling "python2" or "python3".
A small example:
# my_script.py
import sys
print(sys.argv)
input()
# main.py
import subprocess
subprocess.Popen(["gnome-terminal", "-e", "python3 my_script.py hello world"])
Running python3 main.py will spawn a new terminal, with ['my_script.py', 'hello', 'world'] printed, and waited for an input.
I need some advice with a Python script. I'm still new and learned it by myself. I found the script on Google. After I retype it, it doesn't print the result in the console. How can the result of the script be shown in the console? Details as below:
C:\Python27>test1.py af8978b1797b72acfff9595a5a2a373ec3d9106d
C:\Python27>
After I press enter, nothing happens. Should the result be shown or not?
Here's the code that I retyped:
#!/usr/bin/python
#coding: ascii
import requests
import sys
import re
url = 'http://hashtoolkit.com/reverse-hash?hash='
try:
hash = sys.argv[1]
except:
print ("usage: python "+sys.argv[0]+" hash")
sys.exit()
http = request.get(url+hash)
content = http.content
cracked = re.findall("<span title=\*decrypted (md5|sha1|sha384|sha512) hash\*>(.*)</span>", content) # expression regular
print ("\n\tAlgoritmo: "+cracked[0][0])
print ("\tPassword Cracked: "+cracked[0][1])
The first line in your script is called a Shebang line.
A Shebang line tells the script to run the Python interpreter from that location.
The shebang line you provided is a Linux system path, but it looks from the path you are executing Python from, that you are running on Windows.
You can do one of two things here to fix that:
Remove the Shebange Line.
Remove the first line from your script.
Execute the script using python test1.py COMMAND_LINE_ARGUMENTS
Modify Your Shebang line.
Change the first line of your script from !/usr/bin/python to
#!python (This is assuming that python is in your systems PATH variable.)`
Execute the script using test1.py COMMAND_LINE_ARGUMENTS
Also, you are trying to import the requests module that is not installed in the standard library.
If you haven't installed this yet, you can do so by going to your Python install directory and go to the scripts folder.
Hold shift and right click and go Open command window here
Type pip install requests and hit enter.
After that you should be good to go, execute the script by navigating to it and type test.py COMMAND_LINE_ARGUMENT
If a Python script doesn't have the shebang line:
python test.py COMMAND_LINE_ARGUMENT
you need to run your script using python. try:
C:\Python27>python test1.py af8978b1797b72acfff9595a5a2a373ec3d9106d
python -i <script.py> is theoretically meant to run script.py and proceed into interactive mode, however:
shell$ python -i print_content.py < file.txt
hello world
>>>
shell$
The script runs successfully and is followed by printing >>>, implying that the Python shell is entered following script execution.
I know I could bypass the issue by opening the file from within the script - I'm more curious to know the cause of the issue.
Note: Contents of print_content.py seem innocent enough:
import sys
for i in sys.stdin:
print i
Note: I'm using Python 2.7.3
How do I run a python script from within the IDLE interactive shell?
The following throws an error:
>>> python helloworld.py
SyntaxError: invalid syntax
Python3:
exec(open('helloworld.py').read())
If your file not in the same dir:
exec(open('./app/filename.py').read())
See https://stackoverflow.com/a/437857/739577 for passing global/local variables.
In deprecated Python versions
Python2
Built-in function: execfile
execfile('helloworld.py')
It normally cannot be called with arguments. But here's a workaround:
import sys
sys.argv = ['helloworld.py', 'arg'] # argv[0] should still be the script name
execfile('helloworld.py')
Deprecated since 2.6: popen
import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout
With arguments:
os.popen('python helloworld.py arg').read()
Advance usage: subprocess
import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout
With arguments:
subprocess.call(['python', 'helloworld.py', 'arg'])
Read the docs for details :-)
Tested with this basic helloworld.py:
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
You can use this in python3:
exec(open(filename).read())
The IDLE shell window is not the same as a terminal shell (e.g. running sh or bash). Rather, it is just like being in the Python interactive interpreter (python -i). The easiest way to run a script in IDLE is to use the Open command from the File menu (this may vary a bit depending on which platform you are running) to load your script file into an IDLE editor window and then use the Run -> Run Module command (shortcut F5).
EASIEST WAY
python -i helloworld.py #Python 2
python3 -i helloworld.py #Python 3
Try this
import os
import subprocess
DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')
subprocess.call(['python', DIR])
execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)
For example, execFile('C:/helloworld.py')
In a python console, one can try the following 2 ways.
under the same work directory,
1.
>> import helloworld
# if you have a variable x, you can print it in the IDLE.
>> helloworld.x
# if you have a function func, you can also call it like this.
>> helloworld.func()
2.
>> runfile("./helloworld.py")
For example:
import subprocess
subprocess.call("C:\helloworld.py")
subprocess.call(["python", "-h"])
In Python 3, there is no execFile. One can use exec built-in function, for instance:
import helloworld
exec('helloworld')
In IDLE, the following works :-
import helloworld
I don't know much about why it works, but it does..
To run a python script in a python shell such as Idle or in a Django shell you can do the following using the exec() function. Exec() executes a code object argument. A code object in Python is simply compiled Python code. So you must first compile your script file and then execute it using exec(). From your shell:
>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)
I'm using Python 3.4. See the compile and exec docs for detailed info.
I tested this and it kinda works out :
exec(open('filename').read()) # Don't forget to put the filename between ' '
you can do it by two ways
import file_name
exec(open('file_name').read())
but make sure that file should be stored where your program is running
On Windows environment, you can execute py file on Python3 shell command line with the following syntax:
exec(open('absolute path to file_name').read())
Below explains how to execute a simple helloworld.py file from python shell command line
File Location: C:/Users/testuser/testfolder/helloworld.py
File Content: print("hello world")
We can execute this file on Python3.7 Shell as below:
>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'
>>> exec(open("helloworld.py").read())
hello world
>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world
>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world
There is one more alternative (for windows) -
import os
os.system('py "<path of program with extension>"')