Im trying to write and execute a .vbs file with python. When I run the program, the IDE shows an error that the file I tried to make isn't there, so therefore it couldn't be executed. I followed exactly the documentation in python.org and other similar questions in stack overflow but they didn't give a good answer to my problem. Here is the code I tried to run:
import os
a = open('draw.vbs','w+')
a.write('do\nSet oWMP = CreateObject(\"WMPlayer.OCX.7\")\nSet colCDROMs oWMP.cdromCollection\nif colCDROMs.count >= 1\ncolCDROMs.Item(i).eject\nNext cdrom\nEnd If\nloop')
b = os.system('draw.vbs')
Try using a with statement.
with open('draw.vbs', 'w+') as a:
a.write('do\nSet oWMP = CreateObject(\"WMPlayer.OCX.7\")\nSet colCDROMs
b = os.system('draw.vbs')
Related
I have 2 files, 1 file with the classes and 1 file with the 'interface'
In the first file I have:
from second_file import *
class Catalog:
def ListOfBooks(self):
more_20 = input()
# If press 1 starts showing from 20 until 40
if more_20 == '1':
for item in C[20:41:1]:
print("ID:",item['ID'],"Title:",item['title']," Author: ", item['author'])
elif more_20 == '2':
return librarian_option()
test = Catalog()
test.ListOfBooks()
What I try to achieve is when the user presses 2, I want to go back to the function in my other file.
Second file:
def librarian_option():
.......
I don't want to use globals and I have read that the librarian_option() is in the scope of the second file and that's why I can't call it directly. I can't find a solution to it.
I get the following error:
NameError: name 'librarian_option' is not defined
Have you tried? It's just best practice to be explicit instead of using * wildcard
from second_file import librarian_option
Make sure the second_file is in the same directory.
Note: this is not an answer, but an example to help improve the question with more details.
You need to reduce your problem to the minimum amount of code (and actions) necessary to produce your problem. You also need provide how exactly you are running your script, and what version (of Python and your OS) you are using.
For example, I have created the following two scripts (named exactly as shown):
first_file.py:
from second_file import *
class Catalog:
def ListOfBooks(self):
return librarian_option()
test = Catalog()
a = test.ListOfBooks()
print(a)
second_file.py:
def librarian_option():
return 1
These two files are located in the same, random, directory on my computer (MacOS). I run this as follows:
python3.7 first_file.py
and my output is
1
Hence, I can't reproduce your problem.
See if you can still produce your problem with such simplified scripts (i.e., no extra functions or classes, no __init__.py file, etc). You probably want to do this in a temporary directory elsewhere on your system.
If your problem goes away, slowly build back up to where it reappears again. By then, possibly, you've discovered the actual problem as well. If you then don't understand why this (last) change you made caused the problem, feel free to update your question with all the new information.
So I'm currently working on a simple python code to run a simple R script. The R script is only about 6 lines but uses the package "pracma". Using the subprocesses module in python, It runs the script but with the typical "Error in library(pracma) : there is no package called 'pracma' ". I am just looking for a simple solution to be able to run R scripts that have non-base packages installed. I know you can somehow do this using rpy2, but I cannot get that to install using pip, and I'm also using Anaconda3.
All in all, I'd just like a simple package that runs R scripts that have packages installed in them. Any help would be greatly appreciated.
This is the relevant piece of my Python code:
sp.run('Rscript Hausdorff.R', shell=True)
bFile = open("HausdorffData/hausdorff.txt", "r")
result = bFile.read()
bFile.close()
hausdorff_dist = float(result)
return hausdorff_dist
This is my R script:
library(pracma)
setwd('HausdorffData')
PointsA <- as.matrix(read.table("HFileA.txt", header = FALSE))
PointsB <- as.matrix(read.table("HFileB.txt", header = FALSE))
H = hausdorff_dist(PointsA, PointsB)
write(H, file = "hausdorff.txt",ncolumns = 1, append = FALSE)
This produces the following error:
Error in library(pracma) : there is no package called 'pracma'
Execution halted
Thanks to #Dilettant for this:
Even when R can seemingly run the script individually without this, when running the R script from something like python, we need to make sure the script knows what path our library is in. This is achieved by adding this line to the start of the code:
.libPaths(dir\to\package)
If the code has any other lines involving changing working directory, those are unaffected by changing the library path.
I am currently trying to run a .py file but in a loop.
Just for a test I am using
I = 0
while I<10:
os.pause(10)
open(home/Tyler/desktop/test.py)
I = I + 1
I am sure this is a very simple question but I can't figure this one out.
I would also like to add in the very end of this I have to make this run infinitely and let it run for some other things.
There are a few reasons why your code isn't working:
Incorrect indentation (this may just be how you copied it on to StackOverflow though).
Using os without importing it.
Not using quotes for a string.
Mis-using the open function; open opens a file for reading and/or writing. To execute a file you probably want to use the os.system.
Here's a version that should work:
import os
i = 0
while i < 10:
os.pause(10)
os.system("home/Tyler/desktop/test.py")
i += 1
Python is indentation-sensitive, and your code is missing indentation
after the while statement!
Running the open command will not run the Python script. You can
read what it does here in the docs:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
This stack overflow question talks about how to run Python that's
stored in another file
How can I make one python file run another?
I recommend wrapping the code you want to run in a function, e.g.
def foo():
print 'hello'
and then saving this in foo.py. From your main script, you can then do:
import foo
i = 0
while i < 10:
foo.foo()
i += 1
If you want to run something in an infinite loop, you need the condition for the while loop to always be true:
while True:
# do thing forever
A note on importing: The example I have given will work if the foo.py file is in the same directory as the main Python file. If it is not, then you should have a read here about how to create Python modules http://www.tutorialspoint.com/python/python_modules.htm
So I wrote a very simple python test file called test testProg.py, and it looks like this:
import sys
def adder(a, b):
sum = a+b
print sum
if __name__ == "__main__":
a = int(sys.argv[1])
b = int(sys.argv[2])
adder(a, b)
From another question here, I did the command:
python testProg.py 3 4
However I get the following error message:
File "testProg.py", line 5
print sum
^
SyntaxError: invalid syntax
I am honestly not sure what the issue it... I can run python from the command prompt easily with no issue, but why cant I replicate that questions' solution?
Thanks.
Edit: Python 3.4 is used
It looks like you have Python 3 installed. The code you are running was written for Python 2, which has slightly different syntax. For this example, you need to change that to print(sum). In general, you should search around for information on the difference between Python 2 and 3, and be careful to note what version is used in code you find on the internet. Code written for Python 2 will often not run as-is on Python 3.
I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this function I have to type
>>> load('something')
I would rather be able to simply type:
>>> load something
I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.
I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.
Is there a way to do this without writing a custom C program and embedding the interpreter into it?
Edit
Out of channel, I had the suggestion of appending this to the end of my startup file:
import sys
sys.exit()
It works well enough, but I'm still interested in alternative solutions.
You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.
I think you want the cmd module.
See a tutorial here:
http://wiki.python.org/moin/CmdModule
Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:
Edit .bashrc to contain the following lines:
alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'
Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.