Python open another python file

How to execute another python file and then close the existing one?

I am working on a program that requires to call another python script and truncate the execution of the current file. I tried doing the same using the os.close() function. As follows:

def call_otherfile(self): os.system("python file2.py") #Execute new script os.close() #close Current Script 

Using the above code I am able to open the second file but am unable to close the current one.I know I am silly mistake but unable to figure out what’s it.

os.system() is not going to finish until the second script finishes. You want os.execv() (or one of its variants) to replace the current script with the execution of the second.

3 Answers 3

To do this you will need to spawn a subprocess directly. This can either be done with a more low-level fork and exec model, as is traditional in Unix, or with a higher-level API like subprocess .

import subprocess import sys def spawn_program_and_die(program, exit_code=0): """ Start an external program and exit the script with the specified return code. Takes the parameter program, which is a list that corresponds to the argv of your command. """ # Start the external program subprocess.Popen(program) # We have started the program, and can suspend this interpreter sys.exit(exit_code) spawn_program_and_die(['python', 'path/to/my/script.py']) # Or, as in OP's example spawn_program_and_die(['python', 'file2.py']) 

Also, just a note on your original code. os.close corresponds to the Unix syscall close , which tells the kernel that your program that you no longer need a file descriptor. It is not supposed to be used to exit the program.

If you don’t want to define your own function, you could always just call subprocess.Popen directly like Popen([‘python’, ‘file2.py’])

Источник

How can I open files in external programs in Python? [duplicate]

I’m wondering how to open files in programs such as Notepad and Picture Viewer depending on the extension the file has. I’m using Python 3.3 on Windows. I’ve done some research and people have mentioned a module named Image , but when I try and import this module I get an ImportError. Here’s what I have so far:

def openFile(): fileName = listbox_1.get(ACTIVE) if fileName.endswith(".jpg"): fileName.open() 

3 Answers 3

On Windows you could use os.startfile() to open a file using default application:

import os os.startfile(filename) 

There is no shutil.open() that would do it cross-platform. The close approximation is webbrowser.open() :

import webbrowser webbrowser.open(filename) 

that might use automatically open command on OS X, os.startfile() on Windows, xdg-open or similar on Linux.

Читайте также:  Язык javascript основные сведения

If you want to run a specific application then you could use subprocess module e.g., Popen() allows to start a program without waiting for it to complete:

import subprocess p = subprocess.Popen(["notepad.exe", fileName]) # . do other things while notepad is running returncode = p.wait() # wait for notepad to exit 

There are many ways to use the subprocess module to run programs e.g., subprocess.check_call(command) blocks until the command finishes and raises an exception if the command finishes with a nonzero exit code.

only problem is that json files don’t have a default application so that box would appear asking the user what program to open it in

@ToothpickAnemone: yes, there is no os.startfile on Linux. Follow the link to os.startfile() docs in the answer (it says that the function is available only on Windows)

Use this to open any file with the default program:

import os def openFile(): fileName = listbox_1.get(ACTIVE) os.system("start " + fileName) 

If you really want to use a certain program, such as notepad, you can do it like this:

import os def openFile(): fileName = listbox_1.get(ACTIVE) os.system("notepad.exe " + fileName) 

Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.

os.system() will block the calling thread. Something out of the subprocess module might be more appropriate.

I thin ill need to add the program name because files such as json that don’t have a specific program to open will cause problems

@LWH91 I’d recommend adding a check if the file ends with .json , if it does, open the file with a custom program. Else use «start».

Expanding on FatalError’s suggestion with an example.

One additional benefit of using subprocessing rather than os.system is that it uses the same syntax cross-platform ( os.system on Windows requires a «start» at the beginning, whereas OS X requires an «open». Not a huge deal, but one less thing to remember).

Opening a file with subprocess.call .

All you need to do to launch a program is call subprocess.call() and pass in a list of arguments where the first is the path to the program, and the rest are additional arguments that you want to supply to the program you’re launching.

For instance, to launch Notepad.exe

import subprocess path_to_notepad = 'C:\\Windows\\System32\\notepad.exe' path_to_file = 'C:\\Users\\Desktop\\hello.txt' subprocess.call([path_to_notepad, path_to_file]) 

Passing multiple arguments and paths is equally as simple. Just add additional items to the list.

Читайте также:  Html files on dropbox

Launching with multiple arguments

This, for example, launches a JAR file using a specific copy of the Java runtime environment.

import subprocess import os current_path = os.getcwd() subprocess.call([current_path + '/contents/home/bin/java', # Param 1 '-jar', #Param2 current_path + '/Whoo.jar']) #param3 

Argument 1 targets the program I want to launch. Argument2 supplies an argument to that program telling it that it’s going to run a JAR, and finally Argument3 tells the target program where to find the file to open.

Источник

How can I make one python file run another? [duplicate]

How can I make one python file to run another? For example I have two .py files. I want one file to be run, and then have it run the other .py file.

8 Answers 8

There are more than a few ways. I’ll list them in order of inverted preference (i.e., best first, worst last):

  1. Treat it like a module: import file . This is good because it’s secure, fast, and maintainable. Code gets reused as it’s supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py , your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
    • execfile(‘file.py’) in Python 2
    • exec(open(‘file.py’).read()) in Python 3
  3. Spawn a shell process: os.system(‘python file.py’) . Use when desperate.

just to add a bit of detail to case #1: say you want to import fileB.py into fileA.py. assuming the files are in the same directory, inside fileA you’d write import fileB . then, inside fileA, you can call any function inside fileB like so: fileB.name_of_your_func() . there’s more options and details of course, but this will get you up and running.

Using import adds namespacing to the functions, e.g. function() becomes filename.function(). To avoid this use «from name import *». This will also run the code body. Running with os.system() will not keep the defined function (as it was run in another process). execfile is exec() in Python 3, and it doesn’t work.

Get one python file to run another, using python 2.7.3 and Ubuntu 12.10:

#!/usr/bin/python import yoursubfile 

Thus main.py runs yoursubfile.py

There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?

I used subprocess.call it’s almost same like subprocess.Popen

from subprocess import call call(["python", "your_file.py"]) 
import os os.system('python filename.py') 

note: put the file in the same directory of your main python file.

Читайте также:  Writing html in notepad

@Moondra Yes, this method does spawn another process, at least on Windows. On the other hand, importing the file does not. [Tested it by running tasklist | findstr «python» in cmd]

from subprocess import Popen Popen('python filename.py') 

Exactly I was looking for. All the other answers ` import secondary exec(open(‘secondary.py’).read()) os.system(‘python secondary.py’) call([«python», «secondary.py»]) ` they don’t allow creating multiple instances of the secondary python file at the same time. They all wait for the execution to finish only then you can call that file again. Only Popen allows multiple async calls. Thanks again.

Say if there is a def func1() within filename.py , then how to just run this particular function only under Popen(‘python filename.py’) approach?

Источник

How to read from one file and write it into another in Python

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Python comes with the open() function to handle files. We can open the files in following modes:

  • read : Opens the file in reading mode.
  • write : If the file is not present, it will create a file with the provided name and open the file in reading mode. It will overwrite the previous data.
  • append : This is the same as opening in write mode but it doesn’t overwrite the previous data.

Reading line by line

  • Open the file1 , which has content in reading mode.
  • Open the file2 in writing mode.
  • Use for in loop to go through every line in file1 and write to file2 .
  • Content is written to file2 .
  • Close both the files.
  • We will check if the content is written into file2 or not by opening the file2 in reading mode and printing the content.
  • Close the file2 .

Code

In the following code snippet, you can also check that file2.txt is created. Compare the list of before-after files in the output.

import os
# print files in present dir before creating file2
print("List of files before")
print(os.listdir())
print("\n")
#open file1 in reading mode
file1 = open('file1.txt', 'r')
#open file2 in writing mode
file2 = open('file2.txt','w')
#read from file1 and write to file2
for line in file1:
file2.write(line)
#close file1 and file2
file1.close()
file2.close()
#open file2 in reading mode
file2 = open('file2.txt','r')
#print the file2 content
print(file2.read())
#close the file2
file2.close()
#print the files after creating file2, check the output
print("\n")
print("List of files after")
print(os.listdir())
print("\n")

Источник

Оцените статью