I'm trying to invoke a vbscript through python as follows
import os
import sys
import pandas as pd
import numpy as np
rancsv = pd.DataFrame(np.random.randn(150, 5))
rancsv.to_csv('randomcsv.csv', sep=',')
os.system(r"C:\Users\v-2mo\Documents\Python Scripts\test.vbs")
However this simply gives an output of 1 in jupyter notebook and does not run the script.
The script when run directly, runs just fine.
What am I doing wrong?
os.system(r"C:\\Users\\v-2mo\\Documents\\Python Scripts\\test.vbs")
or
os.system(r"C:/Users/v-2mo/Documents/Python Scripts/test.vbs")
answered well here https://stackoverflow.com/a/19114284/17889328
in short, .vbs opens ok in command prompt because shell associates with program wscriipt or cscript and runs it. run silently your program doesn't get the associationand doesn't know how to open. need specify "wscript filename.vbs" and / or run with shell eg "cmd /c..."
Related
I'm a bit turned around on how to execute a shell script file in a Linux environment via Python's subprocess command in Streamlit. Any assistance on what I'm missing is appreciated.
I'm using a shell script called 0_texts.sh to run Pylanguagetool for a grammar check of one text file and return corrections in another text file, like so:
cd /home/user/dir/TXTs/
pylanguagetool text_0.txt > comments_0.txt
This script runs correctly in the Linux terminal, writing a comments_0.txt with appropriate grammar checks from text_0.txt.
I need to create a Python/Streamlit app that runs these shell scripts. In attempting to run this shell script, I've written script.py below:
import os
import subprocess
import sys
subprocess.run(['bash','/home/user/dir/Scripts/0_texts.sh'])
I then run script.py in Streamlit via the code below, keeping with Streamlit's documentation on using subprocess here.
import streamlit as st
import os
import subprocess
import sys
def app():
button1 = st.button("Click me")
if button1:
p = subprocess.run([f"{sys.executable}", "/home/user/dir/pages/script.py"])
st.write(p)
When I execute the script.py via Streamlit, the 0_txts.sh script executes, writing comments_0.txt in the correct directory and providing the following traceback: CompletedProcess(args=['/usr/bin/python3', '/home/user/dir/pages/script.py'], returncode=0). However, the comments_0.txt output contains the error input file is required, as if it can't properly access or read text_0.txt. I've tinkered around trying to find the problem, but have hit a brick wall.
Any suggestions on what I'm missing, or paths forward? Any help greatly appreciated.
I have two files main.py& test.py
Suppose the main file main.py is running and after a point of time I want to run test.py
I cannot use:
import test or os.system("python test.py") because this run python file in same terminal but I want to run the test.py in other terminal
So I mean to say in one terminal main.py is running after a point a new terminal opens and run test.py
Any solutions?
Thanks :D
If I understand correctly you want to run a python script when some condition is fulfilled so I would recommend calling the "test.py" using a subprocess library (bear in mind there are other methods) like this:
import subprocess
if(your_condition):
subprocess.call(['python', 'test.py', testscript_arg1, testscript_val1,...])
as mentioned here: Using a Python subprocess call to invoke a Python script
In Python interpreter (Python 3.9.2, Win 10) I've already run
import numpy as np
In a plain text file "myscript.py" in the same (current working) directory is the single line
A = np.array((1,2,3,4))
Running at the interpreter
import myscript
gives the error message (in part)
NameError: name 'np' is not defined
I'm sure it's a namespace-ish thing; I'm a long-time R user just starting to explore Python. Just puzzled why np isn't defined, despite having imported that alias at the interpreter previously.
I'm looking for something equivalent to R's source() function whereby I can have the Python interpreter and the source code text file both open, make changes to the source code file, and rerun it in the interpreter with each such change. (I'm aware of using importlib.reload() for the subsequent re-runs, but the "name undefined" issue keeps me from getting out of the starting gate.)
If you import myscript in the interpreter, Python just executes that code (similar to using python3 myscript). If you haven't put import numpy as np at the top of your script, then np is not defined. Because it is not defined.
So to start off, you need to add that line to myscript.py:
import numpy as np
A = np.array((1,2,3,4))
Then you can run your script interactively in the interpreter with
>>> exec(open('myscript.py').read())
or, as you suggested, with
>>> import importlib
>>> import myscript
>>> importlib.reload(myscript)
The first two lines must be at the start of your interpreter session, and everytime you edit myscript.py you run importlib.reload(myscript).
I am following Google's Machine Learning Crash Course, so that I can move on to TensorFlow. However, when I try to execute the code in First Steps With TensorFlow, I get no output from the following line:
california_housing_dataframe.describe()
Here is my full code in case it helps:
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe = california_housing_dataframe.reindex(np.random.permutation(california_housing_dataframe.index))
california_housing_dataframe["median_house_value"] /= 1000.0
california_housing_dataframe.describe()
So far, I have tried the following:
Execute the .py file with the python command.
Execute the .py file with the ipython command. I also tried to use arguments -i -c (i.e. ipython -i -c "%run filename.py").
Open ipython.exe and use the run command to execute my script.
Open ipython.exe and copy the code line by line.
Out of the above, only copying every line individually into IPython gave proper output. Is there a way to execute my script without having to copy every line in IPython?
Within a program only the function creating the summary in describe() is executed; in a console environment silently the result is automatically printed as well, as this is what you typically want to see there.
In your program you would have to call
print(california_housing_dataframe.describe())
explicitly.
The interactive python console, jupyter console etc are geared up to allow you to type a variable name, or it's attribute to display it. This is not the case when running a script non-interactively. Instead you must use the print() function.
print(varaible_name.attribute)
I have plotted a graph from a CSV file using SPYDER from PYTHON
Here is my code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('GM_NB_Replica_Test.csv', skiprows=8)
data = df.ix[:,19:116].T
data.columns=df['SN']
data.plot()
plt.show()`
Here is my Output inside the python console:
How do i get this to run externally (Not inside python console, and not in new python console)
I have already tried changing the run settings (See photo below)
However it just gives me a black Python CMD and then no graph.
any thoughts?
current error when running in CMD
From your command prompt (CMD):
cd C://location_of_your_script
python script.py