Os system python mac

Модуль os

Python 3 логотип

Модуль os предоставляет множество функций для работы с операционной системой, причём их поведение, как правило, не зависит от ОС, поэтому программы остаются переносимыми. Здесь будут приведены наиболее часто используемые из них.

Будьте внимательны: некоторые функции из этого модуля поддерживаются не всеми ОС.

os.name — имя операционной системы. Доступные варианты: ‘posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’.

os.environ — словарь переменных окружения. Изменяемый (можно добавлять и удалять переменные окружения).

os.getlogin() — имя пользователя, вошедшего в терминал (Unix).

os.getpid() — текущий id процесса.

os.uname() — информация об ОС. возвращает объект с атрибутами: sysname — имя операционной системы, nodename — имя машины в сети (определяется реализацией), release — релиз, version — версия, machine — идентификатор машины.

os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True) — проверка доступа к объекту у текущего пользователя. Флаги: os.F_OK — объект существует, os.R_OK — доступен на чтение, os.W_OK — доступен на запись, os.X_OK — доступен на исполнение.

os.chdir(path) — смена текущей директории.

os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True) — смена прав доступа к объекту (mode — восьмеричное число).

os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True) — меняет id владельца и группы (Unix).

os.getcwd() — текущая рабочая директория.

os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True) — создаёт жёсткую ссылку.

os.listdir(path=».») — список файлов и директорий в папке.

os.mkdir(path, mode=0o777, *, dir_fd=None) — создаёт директорию. OSError, если директория существует.

os.makedirs(path, mode=0o777, exist_ok=False) — создаёт директорию, создавая при этом промежуточные директории.

os.remove(path, *, dir_fd=None) — удаляет путь к файлу.

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None) — переименовывает файл или директорию из src в dst.

os.renames(old, new) — переименовывает old в new, создавая промежуточные директории.

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) — переименовывает из src в dst с принудительной заменой.

os.rmdir(path, *, dir_fd=None) — удаляет пустую директорию.

os.removedirs(path) — удаляет директорию, затем пытается удалить родительские директории, и удаляет их рекурсивно, пока они пусты.

os.symlink(source, link_name, target_is_directory=False, *, dir_fd=None) — создаёт символическую ссылку на объект.

os.sync() — записывает все данные на диск (Unix).

os.truncate(path, length) — обрезает файл до длины length.

os.utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True) — модификация времени последнего доступа и изменения файла. Либо times — кортеж (время доступа в секундах, время изменения в секундах), либо ns — кортеж (время доступа в наносекундах, время изменения в наносекундах).

os.walk(top, topdown=True, onerror=None, followlinks=False) — генерация имён файлов в дереве каталогов, сверху вниз (если topdown равен True), либо снизу вверх (если False). Для каждого каталога функция walk возвращает кортеж (путь к каталогу, список каталогов, список файлов).

os.system(command) — исполняет системную команду, возвращает код её завершения (в случае успеха 0).

os.urandom(n) — n случайных байт. Возможно использование этой функции в криптографических целях.

os.path — модуль, реализующий некоторые полезные функции на работы с путями.

Для вставки кода на Python в комментарий заключайте его в теги

Источник

MAC OS - os.system(command) display nothing

The test.txt file is created and contain the result. I tried to reinstall and everything, nothing works. Only if I Run python in my terminal, command works but IDLE seems better for work. Who could help me ? Thank you

The output of os.system() goes directly to your terminal; Python plays no part in the process. If you aren't running from a terminal, the output has nowhere to go. Use the subprocess module to run programs in a way that lets you do something with their output.

2 Answers 2

I get the same issue and this is what I did:

However, the same problem persists.

My suggestion is, instead of using IDLE, why don't you use the terminal? In my case, I use iTerm.

$ python3.8 $ >>> import os $ >>> os.system("ls") 

And everything works fine.

If you start IDLE from Terminal with `$ python3 -m idlelib' them output from os.system will appear in Terminal while the return value is printed in the IDLE Shell. But I unless I were developing a Python script that uses os.system, I would just keep IDLE and Terminal both open and type the appropriate commands in each.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Am I using os.system correctly? My application won't open anymore

A few days ago I had the line os.system(r"C:\Users\red\Desktop\Test UI") in my program. I tested it and it worked fine, it opened the application just like I wanted it to. Now, I'm coming back to it about five days later and all of a sudden it's not working properly. I checked the processes and it says 'C:\Users\red\Desktop\Test' is not recognized as an internal or external command, operable program, or batch file. I have already looked at the other questions about os.system like How do I execute a program from Python? os.system fails due to spaces in path, but I am already using a raw string like one of the answers suggested. I don't understand how it can work one day, and the next it fails to work with no change to it.

You should probably replace os.system with subprocess.run in any case, but I don't see how this could have stopped working if it was working previously. The error message suggests that whatever shell os.system is using behind the scenes has stopped treating this as a single path and started treating it as a path plus an argument, split on the space between Test and UI .

That is strange.It seems confused with the space in the name. You could try os.system(r'"C:\Users\red\Desktop\Test UI"') - I just encased the string in single quotes so that the double quotes actually go to the windows process execute.

Note that in the answer on the linked question, subprocess.call is being used, not os.system . When you aren't using shell=True on the former, these are very different things. subprocess.call doesn't try to do any kind of string-splitting with the default shell=False , whereas os.system expects everything to be passed in the local shell's syntax (which requires either quoting or escaping whitespace, though the details of how are platform-specific).

@tdelaney It is actually just Test UI, it's a shortcut that opens a google chrome tab and brings me to a certain page. I tried using your single quotes and then double quotes method like you recommended, but I still get the same error as mentioned in the question.

Источник

Open document with default OS application in Python, both in Windows and Mac OS

I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?

There's been an issue for this to be included in the standard library in the Python tracker from 2008: bugs.python.org/issue3177

17 Answers 17

Use the subprocess module available on Python 2.4+, not os.system() , so you don't have to deal with shell escaping.

import subprocess, os, platform if platform.system() == 'Darwin': # macOS subprocess.call(('open', filepath)) elif platform.system() == 'Windows': # Windows os.startfile(filepath) else: # linux variants subprocess.call(('xdg-open', filepath)) 

The double parentheses are because subprocess.call() wants a sequence as its first argument, so we're using a tuple here. On Linux systems with Gnome there is also a gnome-open command that does the same thing, but xdg-open is the Free Desktop Foundation standard and works across Linux desktop environments.

nitpick: on all linuxen (and I guess most BSDs) you should use xdg-open - linux.die.net/man/1/xdg-open

start on Windows is a shell command, not an executable. You can use subprocess.call(('start', filepath), shell=True), although if you're executing in a shell you might as well use os.system.

I ran xdg-open test.py and it opened firefox download dialog for me. What's wrong? I'm on manjaro linux.

@Jason Sounds like your xdg-open configuration is confused, but that's not really something we can troubleshoot in a comment. Maybe see unix.stackexchange.com/questions/36380/…

open and start are command-interpreter things for Mac OS/X and Windows respectively, to do this.

To call them from Python, you can either use subprocess module or os.system() .

Here are considerations on which package to use:

  1. You can call them via os.system , which works, but. Escaping: os.system only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. A:\abc\def\a.txt ), or else these need to be escaped. There is shlex.quote for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex
    • MacOS/X: os.system("open " + shlex.quote(filename))
    • Windows: os.system("start " + filename) where properly speaking filename should be escaped, too.
  2. You can also call them via subprocess module, but. For Python 2.7 and newer, simply use
subprocess.check_call(['open', filename]) 
subprocess.run(['open', filename], check=True) 

If you need to be compatible all the way back to Python 2.4, you can use subprocess.call() and implement your own error checking:

try: retcode = subprocess.call("open " + filename, shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e 
  • Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type 'filename ; rm -rf /' " problem, and if the file name can be corrupted, using subprocess.call gives us little additional protection.
  • Error handling: It doesn't actually give us any more error detection, we're still depending on the retcode in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).
  • Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.

To the objection "But subprocess is preferred." However, os.system() is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using os.system() is therefore also a correct answer.

A marked disadvantage is that the Windows start command requires you to pass in shell=True which negates most of the benefits of using subprocess .

Источник

Читайте также:  Git squash html academy
Оцените статью