0

I am trying to run a python script first.py from within another python script second.py.

second.py contains the statement os.system("python first.py").

first.py : default open App was notepad previously. But, I changed Default Program to python.exe and now nothing happens. first.py doesn't even run.

Can anyone help?

1
  • What was happening before you changed Default Program to python.exe? Commented Jan 13, 2015 at 18:09

3 Answers 3

1

If all the scripts are from "trusted" sources, you could safely use execfile().

with open('second.py', 'w') as f: f.write('print "hello world"') try: execfile('second.py') # -> hello world except Exception as e: # could also be "pass", "time.sleep()", etc print 'exception {} occurred'.format(e) print 'continuing on...' 

One advantage of this is that it's independent of which Default Program is associated with Python scripts. Also the argument to execfile() can be the complete path to a script in another folder, for example:

 execfile('c:/path/to/different/directory/first.py') 
Sign up to request clarification or add additional context in comments.

8 Comments

this brings another question.. The code is breaking if first.py has an error. I want my code to ignore the error and proceed with second.py , thrid.py and so on.... can you please help?
I can try. What kind of error occurs or exception is raised?
in these files, I am trying to connect to different FTP servers.. On a few occasions when the server doesn't respond or is unavailable i get error 10061 or 10060.. but if i try later , evrything works fine.. I just don't want other scripts to fail when one of the FTP servers didn't connect.
OK, I updated my answer. However it would be even better to put a specific exception (or tuple of them), rather than a generic one, Exception, shown.
Thank you so much..it solved my problem.. I will do some research on exceptions to use a specific one for my case..Thanks again
|
1

Instead of using os.system(), a clean way to execute another script is to import it as a module:

import second 

The will cause "second.py" to be executed.

>>> with open('test.py', 'w') as f: f.write('print "hello world"') ... >>> import test hello world 

1 Comment

One thing to be careful of is namespace conditionals. If code in the imported script is prefixed with 'if __name__ == "__main__":' then the code will not run after imported, but will when executed through a call to os.system().
1

You can run your another python program using subprocess.call module.

import subprocess subprocess.call("second.py", shell=True) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.