How to run python from C# without .exe file - python

I am a Python beginner and wrote some Python code that I want to run from my C# code.
In all the answers I have seen already, the way was to make a .exe file from the .py one and run it by system call.
However, I want it so that I do not need to make the .exe file and can write the commands with arguments as I could in the command line.
C:\Users\ntuser> python C:\Users\ntuser\Documents\run_python.py 3
Is there a way to do it?
I found a way to pass just one command—but I need to make two: 1. Go to "C:\Users\ntuser" 2. Run the Python code.
Thanks!

OK, so I found a solution.
Thanks to UnholySheep for the help.
What you need to do is:
Make the python as system variable
Go by code to your home directory:
Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
Add this code for calling the python code:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//if you want to hide the window
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C python pytonPath\\python_code.py";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();//if you want to wait

Related

IDLE autocomplete in a new file do not work

If I testing my codes on IDLE the autocomplete its works but if I open a new file don't.
See there pictures below:
I just press CTRL + SPACE.
So.. don't work in this case:
I'll think there are some configuration for solve this, any one knows?
Python idle doesn't work that way. You get autocomplete in idle shell because values are deduced in every run. When you use files your program is not evaluated until you run. Because you can assign any type to a variable at run time, there is no way for idle to confirm the type of variable.
Understand with an example
>> a = dict()
>> a = set()
>> a. # <-- autocomplete knows type of a is set
but the same code in a file
a = dict()
a = set()
a. # <-- How does idle come to know what this variable is without running
but when you run this file once your global variables will show autocomplete feature, but not the local scope variables.
Have you tried saving the script as a *.py file before trying to use IDLE's autocomplete?
More than that, have you considered using a text editor with Python plugins, like Sublime Text and Atom? Or even a python-compatible IDE, like PyCharm, Spyder or even JupyterNotebook.

Python: Passing values from GUI to other python script

I have a python script (we'll say "script.py") that I want to grab values from using a separate GUI python script ("GUI.py"). When I run my GUI.py script, I want to have these text fields in the GUI sent over to script.py after clicking a button in the GUI. I am thinking that my best solution might be to have the GUI.py create another script ("lib.py") that holds all these values and it just writes to it. It then runs the "script.py" script. So all in all the GUI.py will have a function that when called will look something like this:
def on_button(self):
username = self.usernameInput.get()
file = open(“lib.py”,”w”)
file.write(“username = ” + username)
os.system("script.py")
I think this will work, but I am just wondering, does this seem like a practical solution? Let me know what you guys think.
No, I don't think this is the practical solution.
Do you consider instead making the python script you want to run into a module or package that you can call directly inside your GUI? I think that is the cleanest approach. For using your scripts as modules, see the docs or for 2.7.
Basically a module is a python file, script.py, and as long as it is in the python path (say, your current directory), you can import it:
from script import action
So you could try:
def on_button(self):
username = self.usernameInput.get()
result = action(username) # and any other args you want to pass
print(result)
That is, if the script in question uses a if __name__ == "__main__": statement (or can otherwise be run from the command line), try putting the operations in some def action(args): function and importing it into your GUI.

Running a .py file in a loop

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

How to run a Python script from inside of another Python Script?

I am currently using subprocess to run a Python script inside of my current Python but it is keep giving me an error:
for dir in os.listdir(os.path.join(DIR2,dirname)):
temp = os.path.join(os.path.join(DIR2,dirname),dir)
files = [os.path.join(temp, f) for f in os.listdir(temp) if f.endswith("json")]
for lists in files:
subprocess.Popen(["python", DIR4, os.path.join(temp,lists)])
Above is what I am currently using.
DIR4 is the path of the python that I want to run.
Problem is, the python that I want to run can only take one file at a time.
However this subprocess looks like it tries to execute ALL at ONCE.
I want to run ONE at a time, instead of ALL at ONCE.
Because it is running ALL at ONCE, my python that I want to run does not work the way it is..
What do I need to do to change this?
If you want to wait first for the subprocess to terminate, before going ahead, I think you could use Popen.wait():
...
p = subprocess.Popen(["python", DIR4, os.path.join(temp,lists)])
p.wait()
...
To actually do what you're asking, and not hack it together through subprocess, you can use exec which allows you to run python code with your own provided globals and locals.
In older versions of Python (meaning pre-3), you can use execfile to achieve the same thing.

Python Popen difficulties: File not found

I'm trying to use python to run a program.
from subprocess import Popen
sa_proc = Popen(['C:\\sa\\sa.exe','--?'])
Running this small snippit gives the error:
WindowsError: [Error 2] The system cannot find the file specified
The program exists and I have copy and pasted directly from explorer the absolute path to the exe. I have tried other things and have found that if I put the EXE in the source folder with the python script and use './sa.exe' then it works. The only thing I can think of is that I'm running the python script (and python) from a separate partition (F:).
Any ideas?
Thanks
As the docs say, "On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline() method.". Maybe that method is messing things up, so why not try the simpler approach of:
sa_proc = Popen('C:\\sa\\sa.exe --?')
If this still fails, then: what's os.environ['COMSPEC'] just before you try this? What happens if you add , shell=True to Popen's arguments?
Edit: turns out apparently to be a case of simple mis-spellling, as 'sa' was actually the program spelled SpamAssassin -- double s twice -- and what the OP was writing was spamassasin -- one double s but a single one the second time.
You may not have permission to execute C:\sa\sa.exe. Have you tried running the program manually?

Categories

Resources