calling python script from another script - python

i'm trying to get simple python script to call another script, just in order to understand better how it's working. The 'main' code goes like this:
#!/usr/bin/python
import subprocess
subprocess.call('kvadrat.py')
and the script it calls - kvadrat.py:
#!/usr/bin/python
def kvadriranje(x):
kvadrat = x * x
return kvadrat
print kvadriranje(5)
Called script works on its own, but when called through 'main' script error occurs:
Traceback (most recent call last):
File "/Users/user/Desktop/Python/General Test.py", line 5, in <module>
subprocess.call('kvadrat.py')
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 595, in __init__
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1106, in _execute_child
OSError: [Errno 2] No such file or directory
Obviously something's wrong, but being a beginner don't see what.

you need to give it the full path to the script that you are trying to call, if you want to do this dynamically (and you're in the same directory), you can do:
import os
full_path = os.path.abspath('kvadrat.py')

Have you tried:
from subprocess import call
call(["python","kvadrat.py"]) #if in same directory, else get abs path
You should also check if your file is there:
import os
print os.path.exists('kvadrat.py')

Subprocess.call requires that the file is executable and found in path. In unix systems, you can try to use subprocess.call(['./kvadrat.py']) to execute a kvadrat.py file in the current working directory and make sure the kvadrat.py has executable permissions on; or you can copy it to a directory in your PATH, such as /usr/local/bin - then it is executable from anywhere as you wanted.
Most of the time you do not want to run other python applications using subprocess but instead just importing them as modules, however...

Related

Opening a file in Python gives me errors

I am quite new to Python and I am having problems opening a file in Python.
I want to open a text file called 'coolStuff' in a Folder on my Desktop and this is how I type in the command but I still get an error message. The file exists and so I do not understand why I get that error message.
open("coolStuff.txt","r")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
open("coolStuff.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'coolStuff.txt'
If you want to simply supply a filename like coolStuff.txt without also providing a full directory, then you have to make sure that Python is running in the same directory as the file. If you aren't sure what directory Python is running in, try this:
import os
print(os.getcwd())
You have two options:
let's say your file is in C:\path\to\dir\coolStuff.txt
1.
open(r'C:\path\to\dir\coolStuff.txt','r')
2.
import os
os.chdir(r'c:\path\to\dir')
open('coolStuff.txt', 'r')
Because the file you want to open is not in the current directory.You can find the file 'coolStuff.txt' in the terminal and launch your python environment at the same directory.

How to get into the python shell within Odoo 8 environment?

I would like to use the Odoo Framework from the shell.
I installed the module "Shell command backport" (technical name: shell), but I couldn't make it work.
$ ./odoo.py shell --addons-path=/opt/odoo_8/src/linked-addons -d database_name
Traceback (most recent call last):
File "./odoo.py", line 160, in <module>
main()
File "./odoo.py", line 157, in main
openerp.cli.main()
File "/opt/odoo_8/src/OCA/OCB/openerp/cli/__init__.py", line 58, in main
for m in module.get_modules():
File "/opt/odoo_8/src/OCA/OCB/openerp/modules/module.py", line 351, in get_modules
plist.extend(listdir(ad))
File "/opt/odoo_8/src/OCA/OCB/openerp/modules/module.py", line 346, in listdir
return map(clean, filter(is_really_module, os.listdir(dir)))
OSError: [Errno 2] No such file or directory: '/opt/odoo8/openerp/addons'
Where is defined the path /opt/odoo8/openerp/addons? I checked this similar question as well.
If I don't write the addons path in the command the error appears again.
I read the answer of this other question, I tried the module and the script option but they didn't work. What should I do to make it work? Any hint would help.
Check your .opererp_serverrc for the user you are executing the command as. In the users home directory you will find this file. There may be reference to the addons_path. The path it appears to be looking for /opt/odoo8/openerp/addons differs from what you have specified in your command. I would check your config files.

Trying to make PLY work for the first time

I'm new to Python and I'm having some problems trying to make PLY works. For now, all I want is to successfully run the example from the PLY homepage.
At first I tried to just download PLY-3.8, put the ply folder in the same directory I saved the example (calc.py) and ran it. The calc.py file is at the C:\Users\...\Python directory and the ply folder is the C:\Users\...\Python\ply, just to make it clearer. But I got an ImportError: No module named 'ply'.
Then I searched for a while, tried to update something called distutils and install the modules through the Windows PowerShell and so on and so forth, but none of that worked and I just reset the whole thing (reinstalling Python and all of that). But then I finally got it to work by simply inserting into the sys.path the directory path where the script I was running (edit: in interactive mode) was, by doing this:
import sys
sys.path.insert(0,'C:\\Users\\ ... \\Python')
This fixed the ImportError but, and this is where I am now, there are a bunch of other errors:
Traceback (most recent call last):
File "C:\Users\...\Python\calc.py", line 48, in <module>
lexer = lex.lex()
File "C:\Users\...\Python\ply\lex.py", line 906, in lex
if linfo.validate_all():
File "C:\Users\...\Python\ply\lex.py", line 580, in validate_all
self.validate_rules()
File "C:\Users\...\Python\ply\lex.py", line 822, in validate_rules
self.validate_module(module)
File "C:\Users\...\Python\ply\lex.py", line 833, in validate_module
lines, linen = inspect.getsourcelines(module)
File "c:\users\...\python\python35\lib\inspect.py", line 930, in getsourcelines
lines, lnum = findsource(object)
File "c:\users\...\python\python35\lib\inspect.py", line 743, in findsource
file = getsourcefile(object)
File "c:\users\...\python\python35\lib\inspect.py", line 659, in getsourcefile
filename = getfile(object)
File "c:\users\...\python\python35\lib\inspect.py", line 606, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__main__'> is a built-in module
Now I have absolutely no idea what to do. I tried to search for a solution but had no luck. I appreciate if anyone can help me out.
I'm on Windows 10, using Python 3.5.0 and iep as my IDE (www.iep-project.org) if these informations are of any importance.
In short: I just want to successfully run the example from the PLY homepage and then I think I can figure out the rest.
EDIT: I found out that if I do:
import inspect
inspect.getfile(__main__)
I get the exact same (last) error from before:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "c:\users\...\python\python35\lib\inspect.py", line 606, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__main__'> is a built-in module
I think this is the culprit, but I still don't know how to fix it.
EDIT 2: I got it to work and answered the question explaining how, but if someone have a more complete answer, I would love to hear it.
To anyone having this problem, I found what was the issue. I still don't know why exactly is like that, so if anyone have a more complete answer to provide I would appreciate (I'm still a newbie at Python).
Anyway, it seems this code can't be executed in Interactive mode, it needs to be executed as a script. To do that on IEP it's Run > Run file as script or Ctrl+Shift+E. On IDLE you need to Open... the file (Ctrl+O) and then Run Module (F5).
As to why it can't be executed in Interactive mode, here's a little bit about the difference between interactive mode and running as script from the IEP wizard:
Interactive mode vs running as script
You can run the current file or the main file normally, or as a script. When run as script, the shell is restared (sic) to provide a clean environment. The shell is also initialized differently so that it closely resembles a normal script execution.
In interactive mode, sys.path[0] is an empty string (i.e. the current dir), and sys.argv is set to [''].
In script mode, __file__ and sys.argv[0] are set to the scripts filename, sys.path[0] and the working dir are set to the directory containing the script.
That explains a bit about why the inspect.getfile(__main__) was throwing an error: the __main__ had no attribute __file__. And also why I had to insert the current directory into sys.path: sys.path didn't had the current directory in interactive mode.
I hope this helps someone.

Error opening megawarc archive from Python

I've found myself having to use a python script to access a webarchive.
What I have is a 'megawarc' web archive file from http://archive.org/details/archiveteam-fanfiction-warc-11. I need to un-megawarc this, using the python script found at https://github.com/alard/megawarc.
I'm trying to run the 'restore' command, and I have the three files needed (FILE.warc.gz,
FILE.tar, and FILE.json.gz) from the first link.
I have both python 2.7 and 3.3 installed.
--------------update--------------
I've ran both this method..
python megawarc restore FILE
and this method..
Make sure you have the files megawarc and ordereddict.py in the same directory, with the files you want to convert.
Rename the file megawarc to megawarc.py
Open a python console in this directory
Type the following code (line by line) :
import sys
sys.argv = ['megawarc','restore','FILE']
import megawarc
megawarc.main()
using python 2.7, and this is what I get..
c:\Python27>python megawarc restore FILE
Traceback (most recent call last):
File "megawarc", line 563, in <module>
main()
File "megawarc", line 552, in main
mwr.process()
File "megawarc", line 460, in process
self.process_entry(entry, tar_out)
File "megawarc", line 478, in process_entry
entry["target"]["offset"], entry["target"]["size"])
File "megawarc", line 128, in copy_to_stream
raise Exception("End of file: %d bytes expected, but %d bytes read." % (buf_size, l))
Exception: End of file: 4096 bytes expected, but 236 bytes read.
Is there something else i'm missing?
I have the following files all in
c:\python27
FILE.megawarc.json.gz
FILE.megawarc.tar
FILE.megawarc.warc.gz
megawarc
ordereddict.py
Is this some type of corrupt file error? Is there something i'm missing?
On the second link you provided, there are two important files :
megawarc
ordereddict.py
The executable script is megawarc. To run it, you have to launch it in a shell with
python megawarc restore FILE
Alternatively, if you're using a UNIX-based system. You can do
chmod +x megawarc
To give megawarc script executable property and then run it with
./megawarc restore FILE
Here, FILE is the actual name you should type if the 3 files you have are FILE.warc.gz, FILE.tar, and FILE.json.gz. You have to change this parameter by the common prefix to your 3 input files if needed.
EDIT :
Okay, i found an alternative that would work if you don't have a standard shell to start the script in command line.
What you have to do is :
Make sure you have the files megawarc and ordereddict.py in the same directory, with the files you want to convert.
Rename the file megawarc to megawarc.py
Open a python console in this directory
Type the following code (line by line) :
import sys
sys.argv = ['megawarc','restore','FILE']
import megawarc
megawarc.main()
This should work, i've just tried it.
Hope it will help.

Running wexpect on windows

I have installed wexpect on Windows 7. Now, when I am trying to run any command, I am getting the below error. I am using MKS toolkit, so ls is a valid command.
>>> import pexpect
>>> pexpect.run('ls ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line
219, in run
child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line
429, in __init__
self._spawn (command, args)
File "C:\Python27\lib\site-packages\winpexpect-1.5-py2.7.egg\pexpect.py", line
516, in _spawn
raise ExceptionPexpect ('The command was not found or was not executable: %s
.' % self.command)
pexpect.ExceptionPexpect: The command was not found or was not executable: ls.
Can some one please help?
Very late reply, but I also faced this problem recently.
Many reasons for failure or probably, wexpect.py needs modification (at least for my case)
Pl check pexpect_error.txt file generated in the same directory of wexpect.py file.
It forks 'python.exe' hence 'python.exe' must be in path (no other name of exe is permitted).
You must be in the same directory of wexpect.py (lib file name must be wexpect.py not pexpect.py) when you are executing your py script.
The cmd (with extension .exe/.com/.bat), must be working at your windows/shell command prompt . Check that (eg actually in Windows when we run 'ls', it is actually running ls.exe/com, in py script, mention as 'ls.exe')
Last but not least: In my case, console window for Window OS creation was failing (found from pexpect_error.txt), hence I changed below
line 2397, make Y coordinate of rect small instead of 70 eg 24 worked for me
UPDATE
The issue has already solved in v2.3.4.
Brief:
Add .exe at the end of the executable:
>>> import pexpect
>>> pexpect.run('ls.exe')
Details:
The root cause of the problem placed in the enumerated which command (method). This method searches the executable in the filesystem. Here is the critical snippet from my wexpect:
# ...
for path in pathlist:
f = os.path.join(path, filename)
if os.access(f, os.X_OK):
return f
return None
# ...
This code appends the parameter of run() as filename and returns it if it is a valid and executable path. Note, that Windows (unlike Linux) executables ends with *.exe

Categories