Long story short, I'm trying to figure out a way to turn these command lines into a script or function in python that can be called by another python application.
These are the command lines in Linux:
source tflite1-env/bin/activate
python3 stream.py --modeldir=TFLite_model
At first I was like this will be easy its just launching the application in python - but I'm not really sure how to deal with the source part. I thought it was just accessing the directory, but its doing something with the .csh file...
I tried a very convoluted method by creating a .sh file like so:
#!/bin/bash
cd ..
cd tflite1
source tflite1-env/bin/activate
python3 stream.py --modeldir=TFLite_model
and then making a function for my main program to call said file:
import os
def startCamera():
os.system('sh script.sh')
With this method I get an error about the source not being found.
I think the issue is I'm basically trying to call too many separate processes that are terminating each other or something? There's got to be a better way. Any suggestions would be greatly appreciated!
I changed the function to:
import subprocess
def startTheCamera()
subprocess.call("/home/pi/Desktop/launchCamera.sh")
I used subprocess instead of os.system and included the full file path and it works now. I think maybe it only needed the full file path, even though it was all in the same directory.
This question already has answers here:
How do I execute a program or call a system command?
(65 answers)
Closed 3 years ago.
I want to launch a external program like notepad.exe using python. I want to have a script that just runs Notepad.exe.
It's really simple with Python's builtin os module.
This will start Microsoft Notepad:
import os
# can be called without the filepath, because notepad is added to your PATH
os.system('notepad.exe')
Or if you want to launch any other program just use:
import os
# r for raw-string, so don't have to escape backslashes
os.system(r'path\to\program\here\program.exe')
Would recommend the subprocess module. Just build up a list of arguments like you would run in the terminal or command line if you are on windows then run it.
import subprocess
args = ['path\to\program\here\program.exe']
subprocess.call(args)
Check out the docs here for all of the other process management functionality.
this can be done using Python OS. Please see the code below for an example.
import os
os.startfile('test.txt')
Startfile will execute the program associated with the file extension.
i am using python 2.7.x
I automating my stuffs and in there i need run to another python program from my python script for that i am using the system function from the 'os' library.
for e.g:
import os
os.system("python anotherscript.py --data <USER_INPUT_FROM_MY_SCRIPT_HERE>")
so i know if any user inputs some other command in place of expected user input that will be converting to os command injection and that's what i want prevent in this case.
Thank you.
Since you need to run a Python script from Python, just import it the Python way and invoke the needed function normally
import anotherscript
anotherscript.<function>("<user_input>")
#Tenchi2xh's answer is the better way to do it, but if that doesn't work (e.g. your script only works on Python 2.x and the other one only works on Python 3.x) then you should use the subprocess module, passing the arguments as a list:
import subprocess
subprocess.call(['python', 'anotherscript.py', '--data', '<USER INPUT>'])
Also take a look at subprocess.check_call and subprocess.check_output to see if they are closer to what you need.
https://docs.python.org/2/library/subprocess.html#subprocess.call
I have made a program named barcode.py which had 4 functions and the main code.
When I import this into another program by using
import barcode
it runs the program barcode and asks for input like in the main program. I was surprised that this happens even when I have not yet called a function and have only imported barcode
Could someone please explain why this happens and how I can import my code without running the the main code in the file barcode.py?
Firstly, your problem is not IDLE specific.
The Python documentation on importing modules tells you that:
A module can contain executable statements as well as function
definitions. These statements are intended to initialize the module.
They are executed only the first time the module name is encountered
in an import statement. (They are also run if the file is executed
as a script.)
What this means is that when you import a module, it will be run once as if you had called it directly as a script (e.g. by typing barcode.py at a command prompt in your example).
If you want script in a module file that is executed if you call is standalone (e.g. by barcode.py) but not when it is imported, use the following pattern, from Python module documentation:
if __name__ == "__main__":
print("I've been run as a script")
Example to check this functionality
You can check at a command prompt that this works - if you save the script above as e.g. modulefile.py and run
$ python modulefile.py
you will see
I've been run as a script
If you start python and type
>>> import modulefile
You will get no output.
I am just getting started with Python.
How do I call a test script from C:\X\Y\Z directory when in Python interpreter command line in interactive mode? How do I specify the full path for the file when it is not in the current working directory?
I can call a test script when using the windows run command with "python -i c:\X\Y\Z\filename.py" and it runs fine. But I want to be able to call it form the Python terminal with the ">>>" prompt.
(I searched and searched for two hours and could not find an answer to this, although it seems like it should be a common question for a beginner and an easy thing to do.)
Thanks
Since you are using backslashes for the file path, python interprets those as "escape characters." When writing the file path in Python, make sure to use forward slashes.
with open("C:/X/Y/Z/filename.py", "r") as file:
exec(file.read())
Double backslashes also work, but I prefer the cleaner look of forward slashes.
If you want to import it into the REPL:
import sys
sys.path.append('c:\X\Y\Z')
import filename
If you want to execute code from a file within the interpreter, you can use execfile
execfile('C:/X/Y/Z/filename.py')
(/ works as path separator in all operating systems, if you use \, you need to escape them ('C:\\X\\Y\\Z\\filename.py')or use raw string literal (r'C:\X\Y\Z\filename.py'))
If you are using IPython (and you should use, it's much more useful than vanilla interactive Python), you can use magic function run (or with % prefix: %run):
run C:\\X\\Y\\Z\\filename.py
%run C:\\X\\Y\\Z\\filename.py
See this link for more information about magic functions.
And by the way, it has even auto completion of filenames.
Exec the heck out of it
Python 2.x:
execfile("C:\\X\Y\\Z")
Python 3+:
with open("C:\\X\Y\\Z", "r") as f:
exec(f.read())
Still, that is very bad practice - it executes code from a string (at some point), instead of using preferred and safer way of importing modules. Still, when you import module and have some of its code after "-f __name__ == '__main__':", that parts won't work (because __name__ in imported module won't be __main__, and it would be, if you ran it as single script).
It is bad for many reasons, in some sense strongly connected to Zen of Python, but if you're beginner, this should speak to you:
When you do anything in interactive mode, you work on some namespace (this term is very important for understanding python, if you don't know it, check it in python language reference). When you exec()/execfile() something without providing globals()/locals(), you may end up with modified namespace.
Modified namespace?
What does it mean? Lets have a script like that:
radius = 3
def field_of_circle(r):
return r*r*3.14
print(field_of_circle(radius))
Now, you have following session:
>>>radius = 5
>>>execfile("script_above.py")
28.26
>>>print(radius)
3
You see what happens? Variables defined by you in interactive session will get overwritten by values from end of script. The same goes for modifying already imported external modules. Lets have a very simple module:
x = 1
and executed script:
import very_simple_module
very_simple_module.x = 3
Now, here's a interpreter interactive session:
>>>import very_simple_module
>>>print(very_simple_module.x)
1
>>>execfile("executed_script.py")
>>>print(very_simple_module.x)
3
Run another interpreter
Interactive sessions are very useful for many things, but not for many things, but running python scripts is not one of them.
Unless... you wanna play tough and use python shell as system shell. Then, you can use subprocess (in standard library) or sh (which can be found on PyPI):
>>>import subprocess
>>>subprocess.call(["python", "C:\\X\Y\\Z"], shell=True)
>>>from sh import python
>>>python("C:\\X\Y\\Z")
Those won't have this problem with modifying interactive interpreters namespace
See script as module
Also, there is one more option: in interactive session add directory with script to pythonpath, and import module named as script:
>>>import sys
>>>if "C:\\X\\Y" not in sys.path:
sys.path.append("C:\\X\\Y")
>>>import Z
Remember that directory in which interpreter was started is automatically on pythonpath, so if you've ran python in the same directory as your script, you just have to use 3rd of lines above.
Interpreters namespace won't change, but code after "-f __name__ == '__main__':" won't be executed. Still you can access scripts variables:
>>>radius = 5
>>>import first_example_script
>>>print(radius)
5
>>>print(first_example_script.radius)
3
Also, you can have module name conflict. For example, if your script was sys.py, then this solution will work, because python will import builtin sys module before yours.