Shebang command to call script from existing script - Python - python-2.7

I am running a python script on my raspberry pi, at the end of which I want to call a second python script in the same directory. I call it using the os.system() command as shown in the code snippet below but get import errors. I understand this is because the system interprets the script name as a shell command and needs to be told to run it using python, using the shebang line at the beginning of my second script.
#!/usr/bin/env python
However doing so does not solve the errors
Here is the ending snippet from the first script:
# Time to Predict E
end3 = time.time()
prediction_time = end3-start3
print ("\nPrediction time: ", prediction_time, "seconds")
i = i+1
print (i)
script = '/home/pi/piNN/exampleScript.py'
os.system('"' + script + '"')
and here is the beginning of my second script:
'#!usr/bin/env python'
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from picamera import PiCamera
import argparse
import sys
import time
import numpy as np
import tensorflow as tf
import PIL.Image as Image
Any help is greatly appreciated :)

Since you have not posted the actual errors that you get when you run your code, this is my best guess. First, ensure that exampleScript.py is executable:
chmod +x /home/pi/piNN/exampleScript.py
Second, add a missing leading slash to the shebang in exampleScript.py, i.e. change
'#!usr/bin/env python'
to
'#!/usr/bin/env python'

The setup that you have here is not ideal.
Consider simply importing your other script (make sure they are in the same directory). Importing it will result in the execution of all executable python code inside the script that is not wrapped in if __name__ == "__main__":. While on the topic, should you need to safeguard some code from being executed, place it in there.

I have 2 python file a.py and b.py and I set execute permission for b.py with.
chmod a+x b.py
Below is my sample:
a.py
#!/usr/bin/python
print 'Script a'
import os
script = './b.py'
os.system('"' + script + '"')
b.py
#!/usr/bin/python
print 'Script b'
Execute "python a.py", the result is:
Script a
Script b

Related

Python script on Django shell not seeing import if import not set as global?

I have searched the stackoverflow and wasn't able to find this. I have noticed something I can not wrap my head around. When run as normal python script import works ok, but when run from Django shell it behaves weird, needs to set import as global to be seen.
You can reproduce it like this. Make a file test.py in folder with manage.py. Code you can test with is this.
This doesn't work, code of test.py:
#!/usr/bin/env python3
import chardet
class LoadList():
def __init__(self):
self.email_list_path = '/home/omer/test.csv'
#staticmethod
def check_file_encoding(file_to_check):
encoding = chardet.detect(open(file_to_check, "rb").read())
return encoding
def get_encoding(self):
return self.check_file_encoding(self.email_list_path)['encoding']
print(LoadList().get_encoding())
This works ok when chardet set as global inside test.py file:
#!/usr/bin/env python3
import chardet
class LoadList():
def __init__(self):
self.email_list_path = '/home/omer/test.csv'
#staticmethod
def check_file_encoding(file_to_check):
global chardet
encoding = chardet.detect(open(file_to_check, "rb").read())
return encoding
def get_encoding(self):
return self.check_file_encoding(self.email_list_path)['encoding']
print(LoadList().get_encoding())
First run is without global chardet and you can see the error. Second run is with global chardet set and you can see it works ok.
What is going on and can someone explain this to me? Why it isn't seen until set as global?
Piping a file into shell is the same as piping it into the python command. It's not the same as running the file with python test.py. I suspect it's something to do with the way the the newlines are interpreted as to how the file is really parsed, but don't have time to check.
Instead of this approach I'd recommend you write a custom management command.

Error while triggering a python script using os.system. Script takes sys.argv arguments

Simple script1.py that takes arguments and calls script2.py by passing them to os.system() :
#! /usr/bin/env python
import os
import sys
os.system("script2.py sys.argv[1] sys.argv[2]")
Running this :
./script1.py "arg1" "arg2"
Getting this single error :
sh: 1: script2.py: not found
Both scripts are present in the same directory.
Applied chmod 777 on both script1.py and script2.py and are executable.
Both scripts call the same interpreter installed at /usr/bin/env python.
When I try these :
os.system("./script2.py sys.argv[1] sys.argv[2]")
os.system("python script2.py sys.argv[1] sys.argv[2]")
The sys.argv[1] and sys.argv[2] are being considered as strings instead of dynamic variables
Have you tried with:
./script2.py "arg1" "arg2"
Inside the os.system?
UPDATE 2
Try with:
import urllib
call_with_args = "./script2.py '%s' '%s'" % (str(arg1), str(arg2))
os.system(call_with_args)

Crontab cannot find the function imported in my python code

i want to import a function from another python code.
It works when i run manually but not in crontab.
So i have this:
file1.py (the main code)
file2.py (contains a function named read())
So i tried this:
file1.py
import file2
url = 'api:v1/stack/alias'
params = urllib.urlencode({'local': file2.read()})
...
So it works when i execute it manually but not when it added in crontag.
After googling i found another solution:
fil1.py
import sys
sys.path.append('/home/pi')
import file2
It works when executed manually but still not by crontab.
So is there another way to do it?
Thank you

how to assign or copy values from command line arguments to the standard input???i have written program but i am unable to do it

from subprocess import call
import sys
import os
import subprocess
if(call("hg clone --insecure https://mixmaster.netwitness.local/" + "sys.argv[1]", shell=True)):
sys.stdin = sys.argv[2]
sys.stdin = sys.argv[3]
else :
print("error")
Is there a reason why the argument is in quotes? Also use % to replace tokens in your string. Change it to this:
if(call("hg clone --insecure https://mixmaster.netwitness.local/%s" % sys.argv[1], shell=True)):
EDIT
If you want to pass all the arguments separated by spaces, use this
if(call("hg clone --insecure https://mixmaster.netwitness.local/%s" % (" ".join(sys.argv[1:])), shell=True)):
subprocess.call is more easily called with a list of parameters. That way you don't have to worry about spaces in the arguments that you want to give to hg. As you indicate in your comments on #Rajesh answer, that you want 3 arguments passed to hg, the following should work:
from subprocess import call
import sys
import os
import subprocess
cmd = ["hg", "clone", "--insecure", "https://mixmaster.netwitness.local/", sys.argv[1], sys.argv[2], sys.argv[3]]
if not (call(cmd, shell=True)):
print("error")
If you really want to provide sys.argv[2] and sys.argv[3] as the input to hg prompts. You should not use call as it can block the hg process, use Popen.

Django timer thread

I would like to compute some information in my Django application on regular basis.
I need to select and insert data each second and want to use Django ORM.
How can I do this?
In a shell script, set the DJANGO_SETTINGS_MODULE variable and call a python script
export DJANGO_SETTINGS_MODULE=yourapp.settings
python compute_some_info.py
In compute_some_info.py, set up django and import your modules (look at how the manage.py script sets up to run Django)
#!/usr/bin/env python
import sys
try:
import settings # Assumed to be in the same directory.
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py'")
sys.exit(1)
sys.path = sys.path + ['/yourapphome']
from yourapp.models import YourModel
YourModel.compute_some_info()
Then call your shell script in a cron job.
Alternatively -- you can just keep running and sleeping (better if it's every second) -- you would still want to be outside of the webserver and in your own process that is set up this way.
One way to do it would be to create a custom command, and invoke python manage.py your_custom_command from cron or windows scheduler.
http://docs.djangoproject.com/en/dev/howto/custom-management-commands/
For example, create myapp/management/commands/myapp_task.py which reads:
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
def handle_noargs(self, **options):
print 'Doing task...'
# invoke the functions you need to run on your project here
print 'Done'
Then you can run it from cron like this:
export DJANGO_SETTINGS_MODULE=myproject.settings; export PYTHONPATH=/path/to/project_parent; python manage.py myapp_task